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

[LintCode] 删除链表中倒数第n个节点

时间:2015-07-07 22:34:59      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

 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         // write your code here
22         ListNode* pre = head;
23         ListNode* cur = head;
24         for (int i = 0; i < n; i++)
25             cur = cur -> next;
26         if (!cur) {
27             delete pre;
28             return pre -> next;
29         }
30         while (cur -> next) {
31             pre = pre -> next;
32             cur = cur -> next;
33         }
34         delete pre -> next;
35         pre -> next = pre -> next -> next;
36         return head;
37     }
38 };

 

[LintCode] 删除链表中倒数第n个节点

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4628530.html

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