Coding problem · Easy · Linked List

Reverse Linked List

Easy Algorithms & data structures Most askedSeen at Amazon, Microsoft, Apple, Meta

Given the head of a singly linked list, reverse the list and return the new head. (Lists are shown as arrays in examples and tests.)

Example 1

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

Example 2

Input: head = []
Output: []

Hints

Hint 1

Walk the list keeping prev and current; point current.next back at prev.

Hint 2

Save current.next before you overwrite it.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(1)

Iteratively flip each next pointer: next = cur.next; cur.next = prev; prev = cur; cur = next. When cur is null, prev is the new head. The recursive version is elegant but uses O(n) stack.

Reference solution

function reverseList(head) {
  let prev = null;
  let cur = head;
  while (cur) {
    const next = cur.next;
    cur.next = prev;
    prev = cur;
    cur = next;
  }
  return prev;
}

Follow-up questions

  • Reverse only positions left..right (Reverse Linked List II).
  • Reverse in groups of k.