13/39
Part 3 of 7 · Reversing and two speedsLearn and do

By default, Python stops a recursive reverse near 1,000 nodes, so use a loop

Reversing can be written with recursion too, and in Python that has a limit.

def reverse_recursive(node):
    if node is None or node.next is None:
        return node
    new_head = reverse_recursive(node.next)
    node.next.next = node
    node.next = None
    return new_head

It's correct, and it makes one call per node. Python keeps every unfinished call on its call stack and, by default, stops at a depth of 1,000. Past that it raises RecursionError.

Run from a script, reverse_recursive reversed 999 nodes and raised RecursionError: maximum recursion depth exceeded at 1,000. The loop reversed 1,000,000.

A thousand nodes is a small list. So in Python, a walk over a list is a loop. A recursive walk can always become a loop with a stack you keep yourself, and a list doesn't even need the stack, because each node has only one next node.

In the editor, finish reverse_first(head, k) with a loop. It reverses the first 3 of six nodes.