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

[LeetCode]Remove Nth Node From End of List

时间:2015-10-28 21:11:20      阅读:217      评论: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.

解题思路:

 1 class Solution {
 2 public:
 3     ListNode* removeNthFromEnd(ListNode* head, int n) {
 4         ListNode dummy(-1);
 5         dummy.next = head;
 6         ListNode *fast = &dummy;
 7         ListNode *slow = &dummy;
 8         
 9         for (int i = 0; i < n ; ++i) {
10             fast = fast->next;
11         }
12         
13         while (fast->next != nullptr) {
14             slow = slow->next;
15             fast = fast->next;
16         }
17         
18         // ListNode *tmp = slow->next;
19         slow->next = slow->next->next;
20         // delete tmp;
21         
22         return dummy.next;
23     }
24 };

 

[LeetCode]Remove Nth Node From End of List

标签:

原文地址:http://www.cnblogs.com/skycore/p/4918409.html

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