Challenge: The Middle Node
Completed
Build a linked list from the input and print the value of the middle node using slow and fast pointers. If there are two middle nodes, print the second one.
Input
One line of values.
Output
The middle value.
Example
Input
1 2 3 4 5
Output
3
Editor
Python
Hints
slow moves 1 step, fast moves 2 steps.
Stop when fast is None or fast.next is None.
Solution explanation
One pass, no counting first: when fast hits the end, slow is in the middle.
Show solution
class Node:
def __init__(self, value):
self.value = value
self.next = None
values = input().split()
head = None
for v in reversed(values):
node = Node(v)
node.next = head
head = node
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
print(slow.value) 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