Challenge: Build and Show a Linked List
Completed
Read some values, build a linked list from them with a Node class, then print it in the form a -> b -> c -> None followed by the number of nodes on the next line (count them by walking the list).
Input
One line of words or numbers.
Output
a -> b -> ... -> None Nodes: <count>
Example
Input
3 1 4
Output
3 -> 1 -> 4 -> None Nodes: 3
Editor
Python
Hints
Add nodes to the front while going through the values backwards.
Walk with cur = cur.next until cur is None.
Solution explanation
Walking the list from the head is O(n), one node at a time.
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
parts = []
count = 0
cur = head
while cur:
parts.append(cur.value)
count += 1
cur = cur.next
print(" -> ".join(parts + ["None"]))
print("Nodes:", count) 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