2024.1.23【链表】6.删除链表的倒数第N个结点
//时间复杂度O(n)
//空间复杂度O(1)
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyHead = new ListNode(0);//使用虚拟头结点,方便处理删除实际头结点的逻辑,不用判断为空的情况
dummyHead->next = head;// head为真正头结点
ListNode* slow = dummyHead;//慢指针
ListNode* fast = dummyHead;//快指针
//先让快指针走 n+1 步
while(n-- && fast != NULL) {
fast = fast->next;
}
fast = fast->next; // 【!注意】fast再提前走一步,因为需要让slow指向删除节点的上一个节点
//快慢指针一起往后走,直到快指针走到 NULL,此时慢指针指向了要删除结点的上一个结点
while (fast != NULL) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next; //删除结点
// ListNode *tmp = slow->next; C++释放内存的逻辑
// slow->next = tmp->next;
// delete nth;
return dummyHead->next;
}
};