Leetcode 19. Remove Nth Node From End of List

Remove Nth Node From End of List

Remove Nth Node From End of List :

給定一個linked list的head,移除linked list從後面數來第n個節點

Python

此題可以用快慢指針來解,快指針先走n個節點,慢指針再開始與快指針一起移動,當快指針到底的時候(fast.next為null),慢指針會停留在要移除的節點n上面(slow所指向的node就是需要刪除節點的前面的節點)。

class Solution(object):
    def removeNthFromEnd(self, head, n):
        fast=slow=head
        for _ in range(n):
            fast=fast.next                  #快指針先走n個節點
        if not fast:
            return head.next
        while fast.next:                   #同時移動快慢指針
            fast=fast.next
            slow=slow.next
        slow.next=slow.next.next           #慢指針停留在要移除的節點n上面
        return head

C++

快慢指針

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* fast = head;
        ListNode* slow = head;
        for(int i=0;i<n;++i){
                fast=fast->next;            #快指針先走n個節點
        }
        if (fast == nullptr){
            return head->next;
        }
        while(fast->next){                 #同時移動快慢指針
            slow = slow->next;
            fast = fast->next;
        }
        ListNode* temp = slow->next;
        slow->next = slow->next->next;    #去除節點
        delete temp;                      #去除節點
        return head;
    }
};