【leetcode】19. Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

Tips:给一个链表,以及一个整数n,从链表中将倒数第n个结点删除。

解法一:遍历两遍,第一次计算链表总长度,第二次删除链表倒数第n个结点。

public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head==null ||n<0) return null;
        ListNode headnew1=head;
        ListNode headnew2=headnew1;
        int count=1,len=0;
        while(head!=null){
            len++;
            head=head.next;
        }
        if(len==n)
            return headnew1.next;
        while(headnew1!=null){
            if(count==len-n){
                ListNode next=headnew1.next;
                headnew1.next=next.next;
                break;
            }
            headnew1=headnew1.next;
            count++;
        }
        return headnew2;
    }

解法二:只遍历一遍,但是设置两个指针,中间间隔n个结点。当fast指针的下一个指针为null时,slow指针的下一个即为要删除的结点。

public ListNode removeNthFromEnd2(ListNode head, int n) {
        //便利一遍。
        if (head==null ||n<0) return null;
        ListNode node=new ListNode(0);
        node.next=head;
        ListNode fast=node;
        ListNode slow=node;
        ListNode newHead=slow;
        for(int i=1;i<=n;i++){
            fast=fast.next;
        }
        while(fast.next!=null){
            fast=fast.next;
            slow=slow.next;
        }
        slow.next=slow.next.next;
        return newHead.next;
    }
原文地址:https://www.cnblogs.com/yumiaomiao/p/8412779.html