Engineered
Data Structures

Reverse Linked List

Reverse every next pointer in a singly linked list.

Try It Yourself

Use the editor below to reverse a singly linked list without creating replacement nodes. Preserve the next node before changing the current node's pointer.

Submit your implementation when it passes the examples. Empty and single-node lists should return safely.

Reverse Linked List

easyLinked List · Pointers25 minLC 206
Problem

Given the head of a singly linked list, reverse the direction of every next pointer.

Return the new head. Each node has the shape { val, next }.

Example 1:

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

Example 2:

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

Constraints

  • 0 ≤ number of nodes ≤ 5,000
  • Do not create replacement nodes.
0 attempts

Solution

Keep previous and current pointers. Save the current node's original next pointer, redirect current.next toward previous, then advance both pointers.

When current reaches null, previous points to the original tail, which is now the new head.

function reverseList(head) {
  let previous = null;
  let current = head;

  while (current !== null) {
    const next = current.next;
    current.next = previous;
    previous = current;
    current = next;
  }

  return previous;
}

Big O notation

MeasureComplexityExplanation
TimeO(n)Every node is visited and rewired exactly once.
Auxiliary spaceO(1)The reversal uses three node references regardless of list length.

How is this lesson?