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;- 1
cur = cur.next; prev.next = cur; next = prev; - 2
prev = cur.next; cur.next = null; cur = prev; - ✓Correct answer:
cur.next = prev; prev = cur; cur = next;
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.