Iterative: maintain prev, current, next pointers.
At each step: save next, point current.next to prev, advance both.
example
// JavaScript — Iterativefunction reverseList(head) {
let prev = null, current = head;
while (current !== null) {
const next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
// Recursivefunction reverseListRecursive(head) {
if (!head || !head.next) return head;
const newHead = reverseListRecursive(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
# Python — Iterativedef reverse_list(head):
prev, current = None, head
while current:
nxt = current.next
current.next = prev
prev = current
current = nxt
return prev
# Recursivedef reverse_list_recursive(head):
ifnot head ornot head.next:
return head
new_head = reverse_list_recursive(head.next)
head.next.next = head
head.next = Nonereturn new_head
output
1→2→3→4 becomes 4→3→2→1
Note Iterative: O(n) time, O(1) space. Recursive: O(n) time, O(n) stack space. This is the single most common linked list question. Draw the pointer changes on paper. Follow-up: reverse a sublist from position m to n.