/**
* 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 *new_head = new ListNode(0,head);
ListNode *slow = new_head;
ListNode *fast = new_head;
int i;
if((head == nullptr) || ((head->next == nullptr) && (n == 1)))
{
return nullptr;
}
for(i = 0;(fast != nullptr) && (i < n + 1);i++)
{
fast = fast->next;
}
while(fast)
{
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return new_head->next;
}
};
力扣刷题 17.删除链表的倒数第N个节点——中等题
最新推荐文章于 2025-12-21 17:04:13 发布
这是一个关于链表数据结构的问题,提供的C++代码实现了一个解决方案,用于从单链表中删除倒数第n个节点。首先创建一个虚拟头节点,然后用两个指针slow和fast,fast先走n步,之后两者同步移动,当fast到达链表尾部时,slow指向的就是目标节点的前一个节点,从而可以删除目标节点。
659

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



