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
|
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)