Python 3D Academyবাংলা

Reversing a list, one link at a time

🌍 In real life. Children play "rail-gari": each child holds the shoulders of the child in front, and the front child is the engine. To send the train the other way, go along from the engine, and let each child in turn let go and hold the child who was behind them instead. One rule keeps the game safe: before a child lets go, someone must remember who comes next, or the back half of the train wanders off and is lost.

Reversing a linked list is exactly this: turn every next link round, one at a time, without losing the rest.

The idea in one sentence: walk the list once with three markers, and at each node save the rest of the list, turn the node's link round to point backwards, and step on.

Its words:

  • prev: the head of the part already reversed (None at the start)
  • cur: the node being turned round
  • nxt: the rest of the list, saved before cur.next changes

How it works, step by step:

  1. prev, cur = None, head
  2. while cur: nxt = cur.next (save), cur.next = prev (turn), prev = cur, cur = nxt (step on)
  3. when cur is None, prev is the new head

Watch each link swing round under the row, with None moving from the right end to the left:

Why it is correct. Before every step two things are true: prev is the head of the nodes already visited, reversed, and cur is the head of the nodes not yet touched, still in their old order. A step moves one node, cur, from the front of the untouched part to the front of the reversed part, so both stay true. When the untouched part is empty (cur is None), every node is in the reversed part, and prev is its head. Saving nxt first is what keeps the untouched part reachable while cur's link points backwards.

What it costs. One pass, four assignments per node: O(n) time. Only three extra variables, whatever the length: O(1) extra memory. Copying the values into a Python list and building a new reversed linked list would also be O(n) time, but O(n) extra memory.

class Node:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

def to_list(head):          # given: the values, front to back
    out = []
    while head:
        out.append(head.val)
        head = head.next
    return out

def reverse(head):
    prev, cur = None, head
    while cur:
        nxt = cur.next      # 1. save the rest
        cur.next = prev     # 2. turn this link round
        prev = cur          # 3. step on
        cur = nxt
    return prev             # the old last node

head = Node(1, Node(2, Node(3, Node(4, Node(5)))))
head = reverse(head)
print(to_list(head))
print(to_list(reverse(None)), to_list(reverse(Node(7))))

Mistakes and edge cases.

  • not saving nxt before cur.next = prev: after that line, cur.next is the reversed part, so the rest of the list is lost
  • returning head: after reversing, the old head is the last node, so you get a list of one node; return prev
  • forgetting that the old head's next must become None: starting with prev = None does that
  • an empty list and a one-node list reverse to themselves, with no special code

Quiz

  1. What does this print?

    class Node:
        def __init__(self, val, next=None):
            self.val = val
            self.next = next
    
    head = Node(6, Node(7, Node(8)))
    prev, cur = None, head
    while cur:
        nxt = cur.next
        cur.next = prev
        prev, cur = cur, nxt
    print(prev.val, prev.next.val, head.next)
  2. This gives back a list of one node instead of the whole list reversed. Which line is wrong?

    def reverse(head):
        prev, cur = None, head
        while cur:
            cur.next = prev
            prev = cur
            cur = cur.next
        return prev
  3. After the loop ends, which marker is the new head?

    • prev
    • cur
    • head
  4. How much extra memory does reversing in place need for n nodes?

    • O(1): three markers
    • O(n): a copy of the values
    • O(n²)

Coding tasks

  1. Write reverse(head): reverse the linked list in place by turning its links round, and give back the new head.

  2. Write reverse_first(head, k): reverse only the first k nodes and keep the rest after them in order (if k is at least the length, reverse it all; k = 0 changes nothing). Give back the new head.