Algorithm Puzzles: Remove Nth Node From End of List

Algorithm Puzzles everyday every week sometimes: Remove Nth Node From End of List

Puzzle

Puzzle from leetcode:

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Solution

Here I use 3 marks to mark node:

  • The node need to be removed: rmMark
  • The previous node of rmMark: rmMarkP
  • The next node of rmMark: rmMarkN
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, const int n) {
ListNode* rmMarkP = nullptr;
ListNode* rmMark = nullptr;
ListNode* rmMarkN = nullptr;
ListNode* cur = head;

int distance = 0;
cur = rmMark = head;

while (cur != nullptr) {
if (distance < n) {
distance++;
} else {
rmMarkP = rmMark;
rmMark = rmMark->next;
rmMarkN = rmMark->next;
}
cur = cur->next;
}

if (rmMarkP == nullptr && rmMark != nullptr) {
// remove head
head = rmMark->next;
} else {
rmMarkP->next = rmMarkN;
}

return head;
}
};