Remove a value from a linked list

Delete every node that holds a given value.

What to build

A function remove(head, value) that handles all of the awkward cases.

Requirements

  • Complete remove(head, value) so that it removes every node with that value and returns the new head.
  • The starter prints the remaining values, or EMPTY.

Input

The first line has n. The second line has n whole numbers. The third line has the value to remove.

Output

The remaining values separated by spaces, or EMPTY.

Constraints

n is from 1 to 1000.

Example

Input:

5
1 2 3 2 4
2

Output:

1 3 4

Why it works

Removing the first node changes the head, so it needs its own step. In the middle, you must stay on a node after removing its neighbour, because the new neighbour might match too.

Examples

Example 1 · Input
5
1 2 3 2 4
2
Expected output
1 3 4
Example 2 · Input
3
7 7 7
7
Expected output
EMPTY

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Deal with matching nodes at the head first, in a loop.

Hint 2

Then walk with a variable, and look at node.next before moving.

Hint 3

Do not move forward straight after removing a node.

Solution

Show one correct solution (try it yourself first)
class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next

def remove(head, value):
    while head and head.value == value:
        head = head.next
    node = head
    while node and node.next:
        if node.next.value == value:
            node.next = node.next.next
        else:
            node = node.next
    return head

n = int(input())
head = None
for v in reversed(input().split()):
    head = Node(int(v), head)
head = remove(head, int(input()))
out = []
node = head
while node:
    out.append(str(node.value))
    node = node.next
print(" ".join(out) if out else "EMPTY")

Lesson: Linked lists →