思路
- 删除倒数
第k个
,即倒数第k + 1
个的后继指向倒数第k -1
个 - 所以要找到倒数第
k + 1
个
虚拟头节点出发,快慢指针
- 快的先走n部
- 然后快慢一起走,直到快的最到最后一个
while(fast && fast ->next)
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
auto dummy = new ListNode(-1);
dummy -> next = head;
auto fast = dummy;
while(n -- ) fast = fast -> next;
auto slow = dummy;
while(fast && fast ->next)
{
fast = fast -> next;
slow = slow -> next;
}
slow -> next = slow -> next -> next;
return dummy -> next;
}
};