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

Remove Nth Node From End of List

时间:2016-04-21 10:02:34      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

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

Example

Given linked list: 1->2->3->4->5->null, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5->null.

 1 /**
 2  * Definition of ListNode
 3  * class ListNode {
 4  * public:
 5  *     int val;
 6  *     ListNode *next;
 7  *     ListNode(int val) {
 8  *         this->val = val;
 9  *         this->next = NULL;
10  *     }
11  * }
12  */
13 class Solution {
14 public:
15     /**
16      * @param head: The first node of linked list.
17      * @param n: An integer.
18      * @return: The head of linked list.
19      */
20     ListNode *removeNthFromEnd(ListNode *head, int n) {
21         if (head == NULL) {
22             return NULL;
23         }
24         ListNode *dummy = new ListNode(0);
25         dummy->next = head;
26         ListNode *node = dummy;
27         int length = 0;
28         while (node->next != NULL) {
29             node = node->next;
30             ++length;
31         }
32         node = dummy;
33         int m = length - n;
34         while (m > 0) {
35             node = node->next;
36             --m;
37         }
38         node->next = node->next->next;
39         return dummy->next;
40     }
41 };

 

Remove Nth Node From End of List

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5415545.html

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