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

19. 删除链表的倒数第N个节点

时间:2020-03-15 18:55:57      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:new   fas   init   ++   nod   倒数   rem   bsp   fast   

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 
10  //1、删除节点,就是找到该节点的前一个节点就可以
11  //2、然后slow->next = slow->next->next;
12 class Solution 
13 {
14 public:
15     ListNode* removeNthFromEnd(ListNode* head, int n) 
16     {
17         ListNode* dummy = new ListNode(-1);
18         dummy->next = head;
19 
20         ListNode* fast = dummy;
21         ListNode* slow = dummy;
22         for(int i = 0;i <= n;i ++) fast = fast->next;
23         while(fast)
24         {
25             fast = fast->next;
26             slow = slow->next;
27         }
28         if(slow->next == NULL) slow = NULL;
29         else slow->next = slow->next->next;
30         return dummy->next; 
31     }
32 };

 

19. 删除链表的倒数第N个节点

标签:new   fas   init   ++   nod   倒数   rem   bsp   fast   

原文地址:https://www.cnblogs.com/yuhong1103/p/12499194.html

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