ORIGIN

LeetCode 19. Remove Nth Node From End of List

ACM 1 min140 words

Problem Description

19. Remove Nth Node From End of List

Analysis

Use two pointers, we let them always have a distance of n, so when right pointer reach the end, the left pointer is the last $n^{th}$ node.

Of course there are some extreme situations like there is only one node, we need to remove them to return null. In order to make this case fit in one universal method, we can add a dummy head.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* fast = dummyHead, *slow = dummyHead;
while(n --) {
fast = fast->next;
}
while(fast->next != nullptr) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummyHead->next;
}
};
TOP
COMMENT
  • ABOUT
  • |
o_oyao
  The Jigsaw puzzle is incomplete with even one missing piece. And I want to be the last piece to make the puzzle complete.
Like my post?
Default QR Code
made with ❤️ by o_oyao
©o_oyao 2019-2024

|