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

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。


示例:

1
2
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]


分析:

1
快慢指针,快指针先走n,慢指针开始走,当快指针走到尾部时,慢指针走到倒数第n个

代码

  • C++

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

if (fast == nullptr)
return head->next;

while (fast->next != nullptr) {
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return head;
}
};

[原题链接](19. 删除链表的倒数第 N 个结点 - 力扣(Leetcode))

0%