LeetCode19. 删除链表的倒数第 N 个结点

题目

分析

我的做法:快慢指针,找到倒数第k+1个节点,然后删除当前节点的下一个节点

y总:先求链表长长度,然后正着遍历找到倒数k+1个节点

代码

自己

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode() : val(0), next(nullptr) {}
 7  *     ListNode(int x) : val(x), next(nullptr) {}
 8  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 9  * };
10  */
11 class Solution {
12 public:
13     ListNode* removeNthFromEnd(ListNode* head, int n) {
14         ListNode *dummy = new ListNode(-1);
15         dummy->next = head;
16         ListNode *fast = dummy, *slow = dummy;
17         while(n){
18             fast = fast->next;
19             n--;
20         }
21         while(fast && fast->next){
22             fast = fast->next;
23             slow = slow->next;
24         }
25 
26        slow->next = slow ->next->next;
27         
28         return dummy->next;
29 
30     }
31 };

y总

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode() : val(0), next(nullptr) {}
 7  *     ListNode(int x) : val(x), next(nullptr) {}
 8  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 9  * };
10  */
11 class Solution {
12 public:
13     ListNode* removeNthFromEnd(ListNode* head, int n) {
14         auto dummy = new ListNode(-1);
15         dummy->next = head;
16 
17         int l = 0;
18         for(auto p = dummy ; p ;p = p->next) l++;
19 
20         auto p = dummy;
21 
22         //倒数第n+1个,也就是正数第 l - (n+1) + 1 个
23         //需要 l - (n + 1) 步
24         for(int i = 0;i < l - (n + 1) ;i++) p = p->next;
25         p->next = p->next->next;
26 
27         return dummy->next; 
28 
29     }
30 };

 

posted @ 2022-03-27 21:42  Uitachi  阅读(14)  评论(0编辑  收藏  举报