Python coding

Linked list, back to front

Write reverse_list(head): given the first node of a singly linked list (or None for an empty list), reverse the list and return its new first node. Each ListNode has val and next.

Re-link the existing nodes instead of copying values: one pass, O(1) extra memory.

The tests call the provided run_reverse_list(values), which builds the list from values and returns the values of the list you return.

  • run_reverse_list([1,2,3,4,5]) → [5,4,3,2,1]
  • run_reverse_list([4,9]) → [9,4]
  • run_reverse_list([]) → []
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Walk the list once with two pointers: prev, the part already reversed, and the current node.

Hint 2

At each node: save its next, point the node back at prev, then advance both. Overwriting next before saving it loses the rest of the list.

Hint 3

When the current node runs out, prev is the old tail: that is the new head, not head.

Solution and why it works
pythonO(n) · O(1)
# --- your code ---
def reverse_list(head: "ListNode | None") -> "ListNode | None":
    prev = None
    while head is not None:
        nxt = head.next          # save the rest before overwriting the link
        head.next = prev
        prev, head = head, nxt
    return prev                  # the old tail is the new head


# --- provided: do not edit ---
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def build_list(values: list[int]) -> ListNode | None:
    head = None
    for v in reversed(values):
        head = ListNode(v, head)
    return head


def to_values(head: ListNode | None, limit: int) -> list[int]:
    out = []
    while head is not None:
        if len(out) == limit:
            raise ValueError("the result has more nodes than the input: is there a cycle?")
        out.append(head.val)
        head = head.next
    return out


def run_reverse_list(values: list[int]) -> list[int]:
    return to_values(reverse_list(build_list(values)), len(values))

Reversing a list only means turning each next pointer around. prev holds the part already reversed and head the part still to do; each step moves one node from one to the other, so one pass and three variables suffice. Two traps: save head.next before overwriting it, or the rest of the list becomes unreachable; and return prev, because the original head is now the tail and its next is None.