Challenge: Remove a Value Everywhere
Completed
Read a line of numbers and a target. Build a linked list and remove every node holding the target (including the head). Print what's left, separated by spaces, or empty.
Input
Line 1: whole numbers. Line 2: the target.
Output
The remaining values, or empty.
Example
Input
7 1 7 2 7 7
Output
1 2
Editor
Python
Hints
Put a dummy node in front of the head.
If prev.next holds the target, skip it; otherwise move prev forward.
Solution explanation
The dummy node means removing the head needs no special case.
Show solution
class Node:
def __init__(self, value):
self.value = value
self.next = None
values = input().split()
target = input().strip()
dummy = Node(None)
tail = dummy
for v in values:
tail.next = Node(v)
tail = tail.next
prev = dummy
while prev.next:
if prev.next.value == target:
prev.next = prev.next.next
else:
prev = prev.next
out = []
cur = dummy.next
while cur:
out.append(cur.value)
cur = cur.next
print(" ".join(out) if out else "empty") Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module