DSA-VerseLearn by watching code run
DashboardData StructuresAlgorithmsVisualizerCORECoding PlaygroundInterview QuestionsComplexity AnalyzerLearning NotesBookmarksLearning ProgressSettings
All interview questions

Interview preparation

Reverse Linked List

EasyLinked ListsRecursion
AmazonMicrosoftAppleMeta Community-reported practice tags — not verified company questions.

1Problem statement

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

2Examples

Input: head = 1 → 2 → 3 → 4 → 5
Output: 5 → 4 → 3 → 2 → 1
Input: head = 1 → 2
Output: 2 → 1

3Constraints

  • 0 ≤ number of nodes ≤ 5000
  • −5000 ≤ Node.val ≤ 5000

4Approaches

Approach 1

Brute Force

Copy values into an array, then write them back in reverse order.

Time O(n)Space O(n)

Approach 2

Better: Recursion

Reverse the rest of the list recursively, then make head.next.next = head and head.next = null.

Time O(n)Space O(n) call stack

Approach 3

Optimal: Iterative pointer reversal

Walk the list with prev, curr, next pointers, flipping curr.next to point backwards each step.

Time O(n)Space O(1)

5Code (optimal approach)

Complete programs that print the example outputs — verified in JavaScript, Python, Java and Go.

class ListNode {
  constructor(val, next = null) {
    this.val = val;
    this.next = next;
  }
}

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

function build(values) {
  let head = null;
  for (let i = values.length - 1; i >= 0; i--) head = new ListNode(values[i], head);
  return head;
}

function show(head) {
  const out = [];
  for (let n = head; n !== null; n = n.next) out.push(n.val);
  out.push("null");
  return out.join(" -> ");
}

console.log(show(reverseList(build([1, 2, 3, 4, 5]))));
console.log(show(reverseList(build([1, 2]))));

6Complexity

Time

O(n)

Space

O(1)

7Visual walkthrough

  1. 1.prev = null, curr = 1
  2. 2.save next = 2; 1.next = null; prev = 1; curr = 2
  3. 3.save next = 3; 2.next = 1; prev = 2; curr = 3
  4. 4.…repeat until curr is null; prev (5) is the new head

Related visualization (Singly Linked List Insertion) — shows the core data-structure operations this solution relies on:

Singly Linked List Insertioninteractive Open full visualizer
head
10
[0]
20
[1]
30
[2]
tail
40
[3]
null
current pointernew nodeinserted

Inserts a new node at a given position: walk to the node just before the position, point the new node at its successor, then re-link the predecessor to the new node.

1 / 11

8Related questions

Merge Two Sorted Lists

On this page

  1. 01Problem statement
  2. 02Examples
  3. 03Constraints
  4. 04Approaches
  5. 05Code (4 languages)
  6. 06Complexity
  7. 07Visual walkthrough
  8. 08Related questions