双指针
如果要删除倒数第n个节点,让fast移动n步,然后让fast和slow同时移动,直到fast指向链表末尾(NULL)。删掉slow所指向的节点就可以了,为了方便删除,使slow指向要删除结点的前一结点,所以一开始slow指向dummyhead,fast指向head结点。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyhead = new ListNode(0,head);
ListNode* slow =dummyhead;
ListNode* fast = head;
while(n-- && fast)
fast=fast->next;
while(fast)
{
slow = slow->next;
fast=fast->next;
}
slow->next = slow->next->next;
return dummyhead->next;
}
};