Algorithm Puzzles: Remove Linked List Elements

Algorithm Puzzles everyday every week sometimes: Remove Linked List Elements

Puzzle

Puzzle from leetcode:

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

Solution

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
/**
* 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* removeElements(ListNode* head, int val) {
ListNode* last = nullptr;
ListNode* newHead = nullptr;
ListNode* current = head;

while(current) {
if(current->val == val) {
if(last) {
last->next = current->next;
}
} else {
last = current;
if(!newHead) {
newHead = last;
}
}
current = current->next;
}

return newHead;
}
};

T.C. O(N)