力扣19. 删除链表的倒数第 N 个结点

 

题目用双指针方法很好想思路,只不过有一种情况要排除,就是链表元素数量==倒数n的时候,要在判断到快指针为NULL的时候,直接返回head->next,排除这种情况之后,其它情况就很好处理了。

题目:【https://leetcode.cn/problems/remove-nth-node-from-end-of-list/?envType=study-plan-v2&envId=top-interview-150

 

 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* f = head;
15         ListNode* s = head;
16         for (int i = 0; i < n; ++i)
17             f = f->next;
18 
19         if (NULL == f)
20             return head->next;
21 
22         f = f->next;
23         while (NULL != f) {
24             f = f->next;
25             s = s->next;
26         }
27 
28         if (NULL != s->next) {
29             ListNode* t = s->next->next;
30             delete s->next;
31             s->next = t;
32         }
33         return head;
34     }
35 };

 

posted @ 2025-05-09 10:10  J&YANG  阅读(11)  评论(0)    收藏  举报