首页 > 其他 > 详细

[LeetCode] Remove Nth Node From End of List

时间:2015-02-06 14:40:19      阅读:305      评论:0      收藏:0      [点我收藏+]

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;

        }   
};

 

[LeetCode] Remove Nth Node From End of List

原文:http://www.cnblogs.com/diegodu/p/4277045.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!