All Blind 75 questions

Reverse Linked List

FreeLinked listsEasy19 of 75

The problem

Reverse a singly linked list by changing its next pointers and return the new head. The list may be empty.

Example

2 → 5 → 9 becomes 9 → 5 → 2

Need a hint?

Save the next node before overwriting its pointer.

Write pseudocode, trace the example, or note an edge case. This scratchpad does not run code.

Notes stay in this browser when storage is available.

Read the solution approach

Maintain previous = null and current = head. Save current.next, point current.next to previous, then advance previous and current. When current becomes null, previous is the reversed head. No new list nodes are necessary.

Complexity

O(n) time and O(1) extra space.

Before moving on, explain why the algorithm is correct and trace a boundary case without looking at the approach.