1.快慢指针实现删除链表的倒数第n个节点
原题链接删除第n个节点
解题思路为设置两个指针,一个fast指针,一个slow指针,先让fast指针移动n次,然后fast和slow同时移动,当fast移动到最后一位的时候,删除slow当前节点。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* slow = dummyHead;
ListNode* fast = dummyHead;
while(n-- && fast != NULL) {
fast = fast->next;
}
fast = fast->next; // fast再提前走一步,因为需要让slow指向删除节点的上一个节点
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;
}
};
标签:快慢,slow,ListNode,fast,next,dummyHead,使用,指针 From: https://www.cnblogs.com/52ld/p/17309494.html