Reverse Linked List


206. Reverse Linked List – LeetCode


Problem Statement

Given the head of a singly linked list, reverse the list, and return the new head.


Examples

Example 1:

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:

Input: head = [1,2]
Output: [2,1]

Example 3:

Input: head = []
Output: []

Constraints


Intuition

To reverse a linked list, we need to flip the direction of every next pointer so that each node points to its previous node, instead of the next.

We can use three pointers:


Approach: Iterative Reversal with Three Pointers

  1. Initialize:

    • prev = null

    • curr = head

  2. Traverse the list:

    • Save next = curr.next

    • Reverse the link: curr.next = prev

    • Move prev and curr one step forward

  3. Once curr == null, prev is the new head of the reversed list.


Java Code

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode curr = head;
        ListNode prev = null;
        ListNode next = null;

        while (curr != null) {
            next = curr.next;     // store next node
            curr.next = prev;     // reverse pointer
            prev = curr;          // move prev forward
            curr = next;          // move curr forward
        }

        return prev; // new head
    }
}

Time and Space Complexity

Metric Value
Time Complexity O(n)
Space Complexity O(1)
Explanation Iterates once through the list; in-place reversal uses no extra space

Dry Run

Input:

head = [1,2,3]

Steps:

Iteration curr.val prev.val next.val New Link
1 1 null 2 1 → null
2 2 1 3 2 → 1
3 3 2 null 3 → 2

Result: 3 → 2 → 1 → null


Recursive Version (Optional)

public 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;
}

Conclusion

This problem is a classic example of in-place pointer manipulation in singly linked lists. Mastering this helps in many more problems such as: