Reverse every next pointer in a singly linked list.
Use the editor below to reverse a singly linked list.
Reverse the existing nodes
Change the pointers without creating replacement nodes. Preserve the next node before changing the current node's pointer. Handle empty and single-node lists.
Submit your implementation when it passes the examples.
Given the head of a singly linked list, reverse the direction of every next pointer.
Return the new head. Each node has the shape { val, next }.
0 ≤ number of nodes ≤ 5,000Results appear here after a run.
previous heads the part already reversed. current heads the part still to visit. On 1 → 2 → 3, save the link to 2 before pointing 1.next to null. Now previous is 1 and current is 2, so both pieces remain reachable. Repeat the same four assignments for each remaining node.
When current reaches null, previous points to the original tail, which is now the new head.
function reverseList(head) {
let previous = null;
let current = head;
while (current !== null) {
const next = current.next;
current.next = previous;
previous = current;
current = next;
}
return previous;
}| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(n) | Every node is visited and rewired exactly once. |
| Auxiliary space | O(1) | The reversal uses three node references regardless of list length. |