/**
* 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个节点——中等题
最新推荐文章于 2024-10-08 10:36:00 发布