Question 8
Back to Exercise
Reversing 1 → 2 → 3 should give 3 → 2 → 1, but only one node remains. Which statement correctly identifies the bug?
class Node:
def __init__(self, val, next=None):
self.val, self.next = val, next
def reverse(head):
prev = None
current = head
while current:
current.next = prev # re-point this node backwards …
prev = current
current = current.next # … then try to move on
return prev
head = reverse(Node(1, Node(2, Node(3))))
values = []
while head:
values.append(head.val)
head = head.next
print(values)
- A prev should start at head
- B The while condition should be current.next
- C current.next is overwritten before it is saved, so current.next then points back to prev (None) and the loop ends; save nxt = current.next first Correct
- D Node needs a __repr__
Correct Answer: Option C
The standard loop is: nxt = current.next; current.next = prev; prev = current; current = nxt.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!