Start learning free

LESSON 429 OF 675 · LINKED LISTS

Remove Linked List Elements

Practice O(n)

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 val are between -231 and 231 - 1.

Note:

Your algorithm should run in O(n) time and use O(1) extra space.

STEP 1 OF 8
    Ctrl + Enter to check