[LeetCode] 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.

 

思路一: 取到 整个link的长度l,然后移删除第l-n 个节点。

思路二:取两个指针,front和back,front优先于back n 步,当front指向最后一个节点时,back指向从后数n+1节点,然后删除第n个节点。

 

 

注意code中使用了dummy节点,避免了如果删除head节点的复杂逻辑判断。也避免了front指向NULL的情况,非常好用,屡试不爽。

class Solution {
    public:
        ListNode *removeNthFromEnd(ListNode *head, int n) {
            ListNode dummy(-1);
            dummy.next = head;
            ListNode* front = &dummy;
            ListNode* back = &dummy;
    
            while(n)
            {   
                front = front->next;
                n--;
            }   

            while(front->next)
            {   
                front = front->next;
                back = back->next;
            }   

            back->next = back->next->next;
            return dummy.next;

        }   
};

 

posted @ 2015-02-06 14:14  穆穆兔兔  阅读(160)  评论(0编辑  收藏  举报