Linked Lists/Practice/Reverse Linked List

Reverse a Linked List - Visual Walkthrough (Python)

easyTime: O(n)Space: O(1)

Walk the list once, keeping three pointers: prev (the list built so far), curr (the node you are holding), and next (so you do not lose the rest). At each node, point it backwards at prev, then slide all three one step forward.

Why it works

A singly linked list only points forward, so you cannot walk backwards - you have to flip direction as you go. Re-pointing one node at a time while saving the tail means every node is touched exactly once: O(n) time, O(1) space.

The problem

Reverse a singly linked list iteratively. Given the head of a linked list, return the head of the reversed list.

Hints

  • You need three pointers: prev (starts None), curr, and next.
  • At each step: save curr.next, point curr.next to prev, advance both prev and curr.
  • After the loop, prev is the new head.

Test cases

InputExpected
reversed [1,2,3,4,5][5,4,3,2,1]
reversed [1,2][2,1]

Reference starter code

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

def reverse_list(head):
    # Iterative O(n) time, O(1) space
    pass

# Helper to build and print
def make_list(vals):
    dummy = ListNode(0)
    c = dummy
    for v in vals:
        c.next = ListNode(v); c = c.next
    return dummy.next

def to_list(h):
    res = []
    while h: res.append(h.val); h = h.next
    return res

print(to_list(reverse_list(make_list([1, 2, 3, 4, 5]))))  # [5,4,3,2,1]
print(to_list(reverse_list(make_list([1, 2]))))            # [2,1]
print(to_list(reverse_list(None)))                         # []

More challenges in this topic

Try it yourself

Solve it in the browser editor with real test cases and instant feedback - free, no signup needed.

Next challenge in this topic: Linked List Cycle II
Studying Linked Lists but not ready to grind? Get the 30-day plan by email.
One email with the study plan. No spam, unsubscribe anytime.