19. Remove Nth Node From End of List(移除倒数第N的结点, 快慢指针)

时间:2025-05-03 00:02:55
Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

思路:

利用快指针先走n步,找到倒数第n个节点

然后删除。

class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* fast = head;
ListNode* slow = head; for(int i = ;i <= n-;++i) {
fast = fast->next;
}
// 一共有N个元素,n=N
if(fast==NULL) return head->next; while(fast->next!=NULL) {
fast = fast->next;
slow = slow->next;
}
ListNode* tmp = slow->next;
slow->next = slow->next->next;
tmp = NULL;
return head;
}
};

注意需要保存前缀

    public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fast = head;
ListNode slow = head;
ListNode fakehead = new ListNode(0);
ListNode pre = fakehead;
fakehead.next= head;
for(int i = 0;i< n ;i++)
fast = fast.next;
while(fast != null){
pre = slow;
slow = slow.next;
fast = fast.next;
}
pre.next = slow.next;
return fakehead.next; }
}