LeetCode 19 - 删除链表的倒数第N个节点 - [链表]

时间:2023-03-09 02:15:44
LeetCode 19 - 删除链表的倒数第N个节点 - [链表]

题目链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/

题解:

两个 $p,q$ 指针均指向头,然后 $q$ 先往前走 $n$ 步,然后 $p,q$ 一起走,直到 $q$ 走到底,此时 $p$ 的位置即倒数第 $n$ 个的位置。

AC代码:

static const auto io_sync_off = []()
{
std::ios::sync_with_stdio();
std::cin.tie();
std::cout.tie();
return nullptr;
}();
struct Solution
{
ListNode* removeNthFromEnd(ListNode* head, int n)
{
ListNode* q=head;
ListNode* p=head;
while(n--) q=q->next;
while(q!=NULL && q->next!=NULL) p=p->next, q=q->next;
if(q==NULL) head=p->next;
else p->next=p->next->next;
return head;
}
};