Remove Linked List Elements
Given the head of a singly linked list and an integer val, remove every node whose value matches val and return the head of what's left. Note the head itself may change if the leading nodes are among those removed.
The surviving nodes should stay in their original relative order.
Input Format
Implement removeElements(head, val). Inputs below show JavaScript function arguments; there is no stdin parsing.
Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.
Output Format
Return the result described in the statement.
Returned list heads are displayed as value arrays; a null head is [].
Sample Input and Output
Example 1 ยท Run Sample
Input
head = [1,2,6,3,4,5,6]
val = 6 Output
[1,2,3,4,5] Example 2
Input
head = [7,7]
val = 7 Output
[] Constraints
- 0 to 10^4 nodes
- 1 <= Node.val <= 50
- 0 <= val <= 50
Test Cases (2)
Case 1
Args: [[1,2,6,3,4,5,6],6]
Expected: [1,2,3,4,5]
Case 2
Args: [[7,7],7]
Expected: []
Topics
Dummy Head
function removeElements(head, val) {
const dummy = {next: head};
let curr = dummy;
while (curr.next) {
if (curr.next.val === val) curr.next = curr.next.next;
else curr = curr.next;
}
return dummy.next;
}Time: O(n) | Space: O(1)
Saved in this browser only. Private to you.