码迷,mamicode.com
首页 > 其他好文 > 详细

19. Remove Nth Node From End of List

时间:2018-10-04 08:50:55      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:list   lin   turn   this   move   ssi   you   ast   example   

Given a linked list, remove the n-th node from the end of list and return its head.

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.

Follow up:

Could you do this in one pass?

 

AC code:

/**
 * 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* demo = new ListNode(0);
        demo->next = head;
        ListNode* fast = demo;
        ListNode* slow = demo;
        
        for (int i = 0; i < n; ++i) {
            fast = fast->next;
        }
        while (fast->next) {
            slow = slow->next;
            fast = fast->next;
        }
        slow->next = slow->next->next;
        return demo->next;
    }
};

Runtime: 8 ms, faster than 34.35% of C++ online submissions for Remove Nth Node From End of List.

 

step1:

         1 -> 2 -> 3 -> 4 -> 5

demo:  0 -> 1 -> 2 -> 3 -> 4 -> 5

fast:              /
slow:       /
 

step2:

         1 -> 2 -> 3 -> 4 -> 5

demo:  0 -> 1 -> 2 -> 3 -> 4 -> 5

fast:               /
slow:         /
 

step3:

         1 -> 2 -> 3 -> 4 -> 5

demo:  0 -> 1 -> 2 -> 3 -> 4 -> 5

fast:                 /
slow:           /
 

step4:

         1 -> 2 -> 3 -> 4 -> 5

demo:  0 -> 1 -> 2 -> 3 -> 4 -> 5

fast:                   /
slow:             /
 

step5:

fast->next == null

slow->next = slow->next->next;

 

         1 -> 2 -> 3 -> 4 -> 5

demo:  0 -> 1 -> 2 -> 3     4 -> 5

fast:               |     /|
slow:              |      |

                 |_______|

  

 

19. Remove Nth Node From End of List

标签:list   lin   turn   this   move   ssi   you   ast   example   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/9741047.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!