题目:

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.

解题思路1:采用两个指针,第一个指针滑动到最末节点,统计出节点数量count,第二个指针从头指针滑动count-n-1步到待删除节点的前一个节点的位置。将该节点的next指针指向待删除节点的下一个节点,将目标节点删除。需要注意如果n等于count说明被删除的节点是头节点,这时只需要返回头节点的next域可以了。该思路的缺陷是需要走两次才能将待删除节点删除。解题思路2将提供一种走一遍就将节点删除的方法。


代码1:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        ListNode *FirstPtr,*SecondPtr;
        FirstPtr=SecondPtr=head;
        int count=0;
        while(FirstPtr!=NULL){
            FirstPtr=FirstPtr->next;
            count++;
        }
        if(count==n)return head->next;
        while(count-n>1){
            SecondPtr=SecondPtr->next;
            count--;
        }
        ListNode *to_delete=SecondPtr->next;
        SecondPtr->next=SecondPtr->next->next;
        delete to_delete;
        return head;
    }
};


解题思路2:建立一个位于头节点之前的节点(该节点的next域指向头节点),设立两个指向该节点的指针,让第一个指针先往后走n步,然后两个指针一起向后走直到最后一个节点,此时第二个指针所在位置的下一个节点就是需要删除的节点。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        ListNode Forehead(0);
        Forehead.next=head;
        ListNode *FirstPtr,*SecondPtr;
        FirstPtr=SecondPtr=&Forehead;
        while(n--){
            FirstPtr=FirstPtr->next;
        };
        while(FirstPtr->next){
            FirstPtr=FirstPtr->next;
            SecondPtr=SecondPtr->next;
        }
        ListNode *to_delete=SecondPtr->next;
        SecondPtr->next=SecondPtr->next->next;
        delete to_delete;
        return Forehead.next;
    }
};