Sponsored
Sponsored
This approach involves using a dummy node to handle the removal of nodes, including edge cases where the head node itself needs to be removed. We use a pointer to traverse the list, comparing each node's value with the target val
. If the node needs to be removed, we adjust the pointers to skip the node. If not, we just move to the next node.
Time Complexity: O(n), where n is the number of nodes in the linked list, as we must traverse all nodes.
Space Complexity: O(1) because we are using constant extra space.
1function ListNode(val, next) {
2 this.val = (val===undefined ? 0 : val);
3 this.next = (next===undefined ? null : next);
4}
5
6var removeElements = function(head, val) {
7 let dummy = new ListNode(0);
8 dummy.next = head;
9 let current = dummy;
10 while (current.next !== null) {
11 if (current.next.val === val) {
12 current.next = current.next.next;
13 } else {
14 current = current.next;
15 }
16 }
17 return dummy.next;
18};
A dummy node is employed to seamlessly remove elements, especially the initial head. Traversing the list with a pointer, elements are withdrawn when their value matches val
. The remaining list is freshly referred through the dummy node's next reference.
This approach employs a recursive strategy to tackle the problem. The idea is to attempt removing elements starting from the rest of the list and linking the current node to the result of this removal. If the head node itself needs removal, simply return the result of removing nodes from the rest of the list by moving the reference forward.
Time Complexity: O(n), as each node is processed exactly once.
Space Complexity: O(n), due to the recursion stack for n nodes in the longest path.
This solution employs a recursive function that processes the rest of the list first and then makes a decision about the current node. If the current node’s value matches val
, the function returns the next node as the new head; otherwise, it returns itself linked to the result of the processed rest.