Updated August 2026 — full tutorial restored for this URL.
Question: How do you reverse a singly linked list? Example: 1 → 2 → 3 → 4 → null becomes 4 → 3 → 2 → 1 → null.
Companion guide: Everything About Linked List (Python).
- Node definition
- Iterative reverse (preferred in interviews)
- Recursive reverse
- Python version
- Complexity
1. Node definition
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
2. Iterative reverse (preferred in interviews)
ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
Dry-run on 1→2→3: after each step the prev chain grows backward until curr is null; return prev.
3. Recursive reverse
ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
4. Python version
def reverse_list(head):
prev, curr = None, head
while curr:
nxt = curr.next
curr.next = prev
prev, curr = curr, nxt
return prev
5. Complexity
- Time O(n), extra space O(1) iterative / O(n) stack recursive
- Watch for cycles if the list might be corrupted