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
|
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) { head = rmMark->next; } else { rmMarkP->next = rmMarkN; }
return head; } };
|