To reverse a linked list, I can change which node each link points to. The part to watch is the next node: once I overwrite a link, I still need a way to reach the rest of the list.
In place linked lists
An in place reversal updates the existing next pointers and uses O(1) extra space. Copying the values into a new list is another approach, but it allocates replacement nodes:
function reverseLinkedListNaive(head) {
const values = [];
let current = head;
// Collect all values
while (current) {
values.push(current.val);
current = current.next;
}
// Create new list in reverse
let newHead = null;
for (let i = 0; i < values.length; i++) {
newHead = new ListNode(values[i], newHead);
}
return newHead;
}
The loop reads values in their original order and inserts each new node at the head. This reverses the list. The values array and replacement nodes use O(n) extra space. Outside the problem platform, this example needs a ListNode(value, next) constructor.
For the in place version, I keep references to the previous, current, and next nodes. Saving the next reference before changing a link keeps the remaining nodes reachable.
function reverseLinkedList(head) {
let prev = null; // Previous node (starts as null)
let current = head; // Current node we're processing
while (current !== null) {
let next = current.next; // Save next node
current.next = prev; // Reverse the link!
prev = current; // Move prev forward
current = next; // Move current forward
}
return prev; // prev is now the new head
}
Each loop saves the next node before changing current.next. It then sets current.next to prev and advances prev to the current node. The loop continues from the saved next node. By the time current is null, prev points to the new head.
Complexity and applications
The list is traversed once, so the time complexity is O(n). The algorithm keeps three references and uses O(1) extra space.
I check the order of those assignments when reviewing a reversal. Saving current.next after overwriting it would lose the path to the unprocessed nodes.

Loading comments...