Overview
Reverse a linked list by relinking its nodes in one pass, without copying them, and without recursion that breaks on long lists.
- nodes that point to the next one
- save next before you relink
- a loop, not recursion, for long lists
Short Course
A linked list is a chain of nodes, each pointing to the next. Reversing it
means turning every arrow around in one pass. Trap: save node.next before
you change it, or you lose the rest of the list.
class Node:
def __init__(self, value, next=None):
self.value, self.next = value, next
node = Node(1, Node(2, Node(3)))
while node: # walk the list
print(node.value)
node = node.next
Task
Write reverse(head): reverse the list by relinking its nodes (no new
nodes) and return the new head. It must handle long lists, so use a loop.
Example: 1 → 2 → 3 becomes 3 → 2 → 1.
Test Suites
Pending
Next
Output