You get the head of a singly linked list and an integer val. Delete every node that holds val. Return the head of the list that is left.
The other nodes keep their order.
Example 1:
Input: head = [5, 9, 2, 9, 4], val = 9 Output: [5, 2, 4]
Example 2:
Input: head = [3, 3, 8, 3], val = 3 Output: [8] Explanation: The first two nodes go too. So the new head is the node with 8.
Example 3:
Input: head = [2, 2], val = 2 Output: [] Explanation: Every node holds 2, so nothing is left. Return null.
Constraints:
- 1 to 1,000,000 nodes.
- The values and
valare between -231 and 231 - 1.
Note:
Your algorithm should run in O(n) time and use O(1) extra space.
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
