Reverse Linked List

In-place iterative reversal using prev/curr/next bookkeeping — the foundational linked-list primitive.

Easy
Time O(n) Space O(1)
LeetCode
2 min read
linked-list

Problem#

Reverse a singly linked list and return the new head.

Examples#

  • [1,2,3,4,5][5,4,3,2,1]

Constraints#

  • Length in [0, 5000].

Approach#

Three pointers: prev starts null, curr walks the list, nxt saves the next pointer before rewriting. Each iteration flips curr->next to point at prev, then shifts the trio forward.

Solution#

Reverse Linked List
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *prev = nullptr, *curr = head;
while (curr) {
ListNode* nxt = curr->next;
curr->next = prev;
prev = curr;
curr = nxt;
}
return prev;
}
};

Editorial#

The mnemonic order is save next → rewrite next → advance prev → advance curr. Reverse the four lines and you’ll either lose the rest of the list or never advance. Each node is touched once.

Complexity#

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

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.