Reverse a singly linked list in place with three references, O(n) time, and O(1) extra space in Java and Python.
Problem and input contract
Pass the head of a finite, acyclic list of nodes with a value and a next reference. The function rewires the original nodes and returns the new head.
1 → 2 → 3 becomes 3 → 2 → 1. An empty list returns null or None. The list 8 returns the same node.
Worked example
1 → 2 → 3 becomes 3 → 2 → 1.
At node 1, save node 2 before pointing 1 to null. At node 2, save node 3 before pointing 2 back to 1. At node 3, point it back to 2. The saved following reference is null, so return 3.
How the solution works
Save the next node before reversing its pointer. The previous pointer leads to the reversed prefix and current leads to the unprocessed suffix.
The temporary following variable preserves the only link to the remaining nodes. The loop changes the original list, so callers should keep the returned head.
Python solution
class Node:
def __init__(self, value, next_node=None):
self.value = value
self.next = next_node
def reverse_list(head):
previous = None
current = head
while current is not None:
following = current.next
current.next = previous
previous = current
current = following
return previousJava solution
class Solution {
static class Node {
int value;
Node next;
Node(int value) { this.value = value; }
}
static Node reverseList(Node head) {
Node previous = null;
Node current = head;
while (current != null) {
Node following = current.next;
current.next = previous;
previous = current;
current = following;
}
return previous;
}
}Approaches and complexity
A stack can store all n node references and reconnect them in reverse order, at the cost of O(n) extra space. The iterative solution visits each node once and uses three references. A recursive reversal also takes O(n) time and uses O(n) stack space.
| Approach | Time | Auxiliary space | Advantage | Limitation | Use case |
|---|---|---|---|---|---|
| Stack | O(n) | O(n) | Explicit reverse order | Stores every reference | When a stack is already available |
| Three references | O(n) | O(1) | Reuses nodes | Mutates the list | In-place reversal |
Common mistakes and interview follow-up
Save the next node before changing current.next. Update your head reference with the returned node. Duplicate values require no special handling because the algorithm moves links.
Related practice: Find children of a given binary tree by target node or by target value.
Comments
Post a Comment