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.

思路:很巧妙的一个方法。用两个指针形成n gap,gap形成以后,以同样的速度移动。当最后一个达到end时,前一个就移动到了从后数的第nth个

代码:1.如果不添加initialStart的话,就需要检查删除node为head的情况。2.添加初始initialStart的话,所有删除情况一样。

注意::还有一种简化代码的方法是 [指针的指针]。,我有点晕。。。。下次看

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    /*use two pointer to form a gap*/
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        ListNode *p1,*pn;
        p1=pn=head;
        while(n>=0 && pn){
            pn=pn->next;
            n--;
        }
        // delete the first element from end;
        if(n>=0) {
            head=head->next;
            return head;
        }
        
        while(pn){
            pn=pn->next;
            p1=p1->next;
        }
        if(p1 && p1->next) p1->next=p1->next->next;
        return head;
    }
};
原文地址:https://www.cnblogs.com/renrenbinbin/p/4341065.html