Skip to content

Reverse Linked List

EasyLeetCode #206Time O(n)Space O(1)

You get the head of a singly linked list. Reverse it so the last node becomes the first, and return the new head.

1 -> 2 -> 3 -> 4 -> 5 -> 5 -> 4 -> 3 -> 2 -> 1

You can’t walk backwards in a singly linked list, so copying values into an array and back costs O(n) extra space. The better idea: reversing a list just means making every next arrow point the other way.

Walk forward with two pointers: prev (the already-reversed part, starting as None) and the current node. For each node, save its next first, point it at prev, then step both pointers forward. When the current node runs off the end, prev is the new head. The recursive version does the same thing on the way back up the call stack, but it uses O(n) stack space, so the iterative one is the one to write.

Show solutionHide solution
def reverse_list(head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
while head:
head.next, prev, head = prev, head, head.next # flip the arrow, step forward
return prev
  • Time: O(n) — each node is visited once and rewired in O(1).
  • Space: O(1) — only a couple of pointers. (Recursion would be O(n) for the call stack.)
  • Save next before overwriting it. Set head.next = prev first and you’ve lost the rest of the list. The Python version avoids this with one tuple assignment.
  • Return prev, not head. After the loop, head is null and the old head is now the tail.
  • Empty and single-node lists work with no special case: the loop is skipped or runs once, and prev ends up correct.

Reverse only the nodes from position left to right. The trick: use a dummy head, walk to the node just before left, then reverse the next right - left + 1 nodes with the same loop. Finally reconnect the reversed block to both sides.

Decide whether the list reads the same both ways, in O(1) space. The trick: find the middle with fast and slow pointers, reverse the second half in place, then compare it with the first half.

Reverse the list in blocks of k; leave a short last block alone. The trick: check that k nodes remain, reverse exactly that many with the loop above, then stitch the block between the previous block’s tail and the rest.