Reverse Linked List
Source: Dev.to
Objective
- Reverse a singly linked list in‑place.
- The last node becomes the first.
- All
nextpointers are reversed. - Return the new head of the reversed list.
Intuition
A singly linked list node stores a value and a reference to the next node.
If we traverse the list while re‑assigning each node’s next pointer to point to its predecessor, the list becomes reversed.
Approach
Use two pointers while iterating through the list:
| Pointer | Meaning |
|---|---|
prev | The node that will become the next of the current node (initially null). |
curr | The node currently being processed (initially head). |
During each iteration:
- Store
curr.nextin a temporary variable (nextTemp). - Set
curr.next = prev. - Move
prevforward tocurr. - Move
currforward tonextTemp.
When curr becomes null, prev points to the new head.
Algorithm (Java)
/**
* Reverses a singly linked list in‑place.
*
* @param head the original head of the list
* @return the new head after reversal
*/
Node reverseLL(Node head) {
Node prev = null; // will become the new head
Node curr = head; // current node being processed
while (curr != null) {
Node nextTemp = curr.next; // store next node
curr.next = prev; // reverse the link
prev = curr; // advance prev
curr = nextTemp; // advance curr
}
// prev is the new head
return prev;
}
Note:
Nodeis assumed to be a class with at least aNode nextfield.
Example Walkthrough
Consider the list 10 → 20 → 30 → 40 → null.
| Step | prev | curr | Action |
|---|---|---|---|
| Initial | null | 10 | – |
| 1 | 10 | 20 | 10.next = null |
| 2 | 20 | 30 | 20.next = 10 |
| 3 | 30 | 40 | 30.next = 20 |
| 4 | 40 | null | 40.next = 30 |
After the loop ends, prev points to 40, yielding the reversed list:
40 → 30 → 20 → 10 → null
Edge Cases
- Empty list:
head == null→ the function returnsnull. - Single‑node list:
head.next == null→ the function returns the same node (no changes needed).
Final Output
The function returns the head of the reversed list, e.g., for the example above the result is 40.