Lesson 47 of 73 2 min

Problem: Reverse a Linked List

Learn how to reverse a singly linked list in-place using pointer manipulation.

Problem Statement

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

Approach: In-Place Reversal

We use three pointers to track the previous, current, and next nodes.

  1. Initialize: prev = null, curr = head.
  2. Iterate:
    • Save the next node: nextTemp = curr.next.
    • Reverse the link: curr.next = prev.
    • Advance pointers: prev = curr, curr = nextTemp.
  3. Return: prev becomes the new head.

Java Implementation

public ListNode reverseList(ListNode head) {
    ListNode prev = null;
    ListNode curr = head;
    
    while (curr != null) {
        ListNode nextTemp = curr.next; // Store next
        curr.next = prev;              // Reverse
        prev = curr;                   // Move prev forward
        curr = nextTemp;               // Move curr forward
    }
    
    return prev;
}

Dry Run

Input: 1 -> 2 -> 3 -> null

Step prev curr nextTemp Action
Initial null 1 - Start
1 1 2 2 1 -> null
2 2 3 3 2 -> 1 -> null
3 3 null null 3 -> 2 -> 1 -> null

Complexity Analysis

  • Time Complexity: $O(n)$.
  • Space Complexity: $O(1)$.

Want to track your progress?

Sign in to save your progress, track completed lessons, and pick up where you left off.