Data Structures & Algorithms Linked Lists
💡
Exercise 62

Reverse Linked List 20 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

Reversing a linked list is THE fundamental linked list operation. It appears in interviews constantly, and you'll use this technique in dozens of other problems. 🔄

💡 Think of it like this: Imagine a chain of paper clips linked together: A → B → C → D. To reverse it, you need to flip each connection one by one, so it becomes D → C → B → A.

# Before: 1 → 2 → 3 → 4 → 5 → None # After: 5 → 4 → 3 → 2 → 1 → None

The Algorithm — Three Pointers:

You need three pointers moving through the list like a caterpillar:

  • prev — the node behind us (starts as None)
  • current — the node we're at right now (starts at head)
  • next_node — saved reference to the next node (so we don't lose it!)

💭 Now it's your turn! Using the approach above, implement your solution in the editor. You've got this! 💪

Step-by-step trace (1→2→3):

  • Start: prev=None, curr=1, next=2. Flip: 1→None. Move: prev=1, curr=2
  • Step 2: prev=1, curr=2, next=3. Flip: 2→1. Move: prev=2, curr=3
  • Step 3: prev=2, curr=3, next=None. Flip: 3→2. Move: prev=3, curr=None
  • Done! curr=None, return prev=3. Result: 3→2→1→None ✓

Complexity: Time O(n) — visit every node once. Space O(1) — only 3 pointer variables.

📋 Instructions
Implement `reverse_list(head)` that reverses a linked list iteratively. Create a list 1→2→3→4→5, reverse it, and print all values.
Three pointers: prev=None, curr=head. While curr: save next_node=curr.next, flip curr.next=prev, advance prev=curr, advance curr=next_node. Return prev.
⚠️ Try solving it yourself first — you'll learn more!
def reverse(head):
    prev = None
    current = head
    while current:
        next_node = current.next  # 1. Save next (don't lose it!)
        current.next = prev       # 2. Reverse the arrow ←
        prev = current            # 3. Move prev forward →
        current = next_node       # 4. Move current forward →
    return prev  # prev is now the new head!
🧪 Test Cases
Input
Run your code
Expected
5 4 3 ...
Expected output (5 lines)
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.