Algorithms and Data Structures · Middle · Question 26 of 75

How do you reverse a singly linked list iteratively?

let prev = null, cur = head;
while (cur) {
  const next = cur.next;
  // ?
}
return prev;

Explanation

Each node's pointer is flipped to the previous node, then both pointers move forward. next is saved first, otherwise the rest of the list would be lost. O(n) time, O(1) memory.

Further reading

Problem with a question

Algorithms and Data Structures · Middle · question 26

Test yourself

Take the Algorithms and Data Structures · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz