LeetCode 19.删除链表的倒数第N个结点
思路
这道题是双指针法的经典应用。
删除链表的倒数第N个结点,只需要让fast指针先移动N+1个结点,然后再让slow指针与fast指针同时移动,一直到fast指针指向链表末尾,最后删除slow所指向的结点(让fast指针先移动N+1个结点的目的是为了让fast指针与slow指针之间的距离保持在N+1个结点的长度上,这样才能当fast移动到链表末尾时,slow指针刚好落在需要删除结点的上一个结点处,方便进行删除操作)
代码实现
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode *fast = dummyHead;
ListNode *slow = dummyHead;
while(n-- && fast != nullptr){
fast = fast->next;
}
fast = fast->next;
while(fast != nullptr){
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
head = dummyHead->next;
delete dummyHead;
return head;
}
};