class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* Head=new ListNode(-1);
Head->next=head;
ListNode* pre=Head,*cur=Head;
int len=0;
while(cur&&len<=n)
{
len++;
cur=cur->next;
}
while(cur)
{
cur=cur->next;
pre=pre->next;
}
pre->next=pre->next->next;
head=Head->next;
delete Head;
return head;
}
};19. Remove Nth Node From End of List
最新推荐文章于 2024-09-05 06:26:26 发布
本文介绍了一种高效的方法来解决链表中倒数第N个节点的删除问题。通过使用双指针技巧,即先移动前导指针N步,然后同时移动两个指针直到前导指针到达链表尾部,此时跟随指针恰好位于待删除节点的前一个位置。
646

被折叠的 条评论
为什么被折叠?



