19. Remove Nth Node From End of List - cocoder39/coco39_LC GitHub Wiki
19. Remove Nth Node From End of List
Notes 2020
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
fast, slow = dummy, dummy
cnt = 0
while fast:
fast = fast.next
if cnt > n:
slow = slow.next
cnt += 1
slow.next = slow.next.next
return dummy.next
========================================================================
TO remove nth node, it is better to locate (n-1)th node, thus dummy. Compared with 237. Delete Node in a Linked List, where we are given the node to be removed, not its previous node.
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (! head) {
return nullptr;
}
ListNode dummy(0);
dummy.next = head;
ListNode* fast = &dummy;
ListNode* slow = &dummy;
while (fast->next) {
if (n > 0) {
n--;
}
else {
slow = slow->next;
}
fast = fast->next;
}
slow->next = slow->next->next;
return dummy.next;
}