19. Remove Nth Node From End of List(移除倒数第N的结点, 快慢指针)

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.

思路:

利用快指针先走n步,找到倒数第n个节点

然后删除。

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {

        ListNode* fast = head;
        ListNode* slow = head;
       
        for(int i = 0;i <= n-1;++i) {
            fast = fast->next;
        }
        // 一共有N个元素,n=N
        if(fast==NULL) return head->next;

        while(fast->next!=NULL) {
            fast = fast->next;
            slow = slow->next;
        }
        ListNode* tmp = slow->next;
        slow->next = slow->next->next;
        tmp = NULL;
        return head;
    }
};

注意需要保存前缀

 1    public ListNode removeNthFromEnd(ListNode head, int n) {
 2         ListNode fast = head;
 3         ListNode slow = head;
 4         ListNode fakehead = new  ListNode(0);
 5         ListNode pre = fakehead;
 6         fakehead.next= head;
 7         for(int i = 0;i< n ;i++)
 8             fast = fast.next;
 9         while(fast != null){
10              pre = slow;
11             slow = slow.next;
12             fast = fast.next;
13         }
14         pre.next = slow.next;
15         return fakehead.next;
16         
17     }
18 }
原文地址:https://www.cnblogs.com/zle1992/p/7718734.html