ListNode* removeNthFromEnd(ListNode* head, int n) {
//判空
if(head == nullptr)
return head;
ListNode* node = nullptr;
//定义快慢指针
ListNode* slow = head;
ListNode* fast = head;
//先让fast先向后移动n步
while(n--)
fast = fast->next;
//此时head就是要删除的那个结点
if (fast == nullptr){
//释放删除结点的空间
node = head->next;
delete head;
return node;
}
//当fast->next==nullptr时,slow->next为要删除的结点
while(fast->next != nullptr)
{
slow = slow->next;
fast = fast->next;
}
//释放删除结点的空间
node = slow->next;
slow->next = slow->next->next;
delete node;
return head;
}
删除链表的倒数第n个结点
最新推荐文章于 2022-11-02 12:20:39 发布