The classic interview question: turn 1 → 2 → 3 into 3 → 2 → 1 by flipping each arrow, with three pointers.
Python · intermediate · 8 min · 37 steps · free
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def reverse(head):
previous = None
current = head
while current is not None:
following = current.next
current.next = previous
previous = current
current = following
return previous
head = Node(1, Node(2, Node(3)))
head = reverse(head)
print(head.value, head.next.value, head.next.next.value)Node. Its methods are stored, but none of them run yet.class Node belongs to it.__init__ is stored in Node. It runs only when it is called on an object.Node is now defined, ready to make objects from.reverse(). Its body does not run yet: it runs each time the function is called.__init__(), with self = {}, value = 3 and next = null. It gets its own names.value with the value 3 is added to the Node that self points to.next with the value null is added to the Node that self points to.__init__() has finished. Python calls __init__(), with self = {}, value = 2 and next = {value: 3, next: null}. It gets its own names.value with the value 2 is added to the Node that self points to.next with the value a Node is added to the Node that self points to.__init__() has finished. Python calls __init__(), with self = {}, value = 1 and next = {value: 2, next: a Node}. It gets its own names.value with the value 1 is added to the Node that self points to.next with the value a Node is added to the Node that self points to.__init__() has finished, so its names are gone. The value it returned, {value: 1, next: a Node}, is stored in head.reverse(), with head = {value: 1, next: a Node}. It gets its own names.previous is created but does not point to any object yet (null).current is created and points to the same Node as head. No copy is made.current is not None is true, so the loop body runs.following remembers node 2 before the link is cut.previous: None. It will be the new tail.previous moves up to node 1.current moves on to node 2.current is not None is true, so the loop body runs.following now points to a different Node: {value: 3, next: null}.previous now points to the same Node as current.current now points to the same Node as following.current is not None is true, so the loop body runs.following is set to null, so it no longer points to any object.next in the Node that current points to changes from null to a Node.previous now points to the same Node as current.current is set to null, so it no longer points to any object.current is not None is false, so the loop ends.previous is the new head: 3 → 2 → 1.reverse() has finished, so its names are gone. The value it returned, {value: 3, next: a Node}, is stored in head.3 2 1.Answer: O(1). Just three pointers.
Answer: None
← Linked Lists · Stacks: Balanced Brackets →