Reversed Linked List Traversal
Algorithm · Starter
Step through it: In-Place Reversal pattern
Step 1 of 6
Goal: reverse 1 → 2 → 3 → 4 so it reads 4 → 3 → 2 → 1, without building a new list. We only flip each arrow, using two helpers: prev (the node behind) and cur (the node we are looking at).
Step 2 of 6
Flip the arrow of node 1 so it points at nothing (null). Then move both helpers one node forward.
Step 3 of 6
Node 2: flip its arrow to point back at 1, then move forward.
Step 4 of 6
Node 3: flip its arrow to point back at 2.
Step 5 of 6
Node 4: flip it to point at 3. cur steps off the end, so prev (4) is the new first node: 4 → 3 → 2 → 1. One pass and no extra list: this is in-place reversal.
Step 6 of 6
Your turn.
The task is to traverse the given linked list in reversed order.
For example for the following linked list:
The order of traversal should be:
37 → 99 → 12The time complexity is O(n) because we visit every node only once.
Reference
Code
/**
* Traversal callback function.
* @callback traversalCallback
* @param {*} nodeValue
*/
/**
* @param {LinkedListNode} node
* @param {traversalCallback} callback
*/
function reverseTraversalRecursive(node, callback) {
if (node) {
reverseTraversalRecursive(node.next, callback);
callback(node.value);
}
}
/**
* @param {LinkedList} linkedList
* @param {traversalCallback} callback
*/
export default function reverseTraversal(linkedList, callback) {
reverseTraversalRecursive(linkedList.head, callback);
}Practice
In-Place Reversal
- Reverse Linked ListEasy
- Merge Two Sorted ListsEasy
- Remove Linked List ElementsEasy
- Remove Duplicates from Sorted ListEasy
- Reverse Linked List IIMedium
- Swap Nodes in PairsMedium
- Add Two NumbersMedium
- Odd Even Linked ListMedium
- Partition ListMedium
- Remove Duplicates from Sorted List IIMedium
- Rotate ListMedium
- Swapping Nodes in a Linked ListMedium
- Reverse Nodes in k-GroupHard
- Merge k Sorted ListsHard
Spotted a mistake or something unclear? Report it on GitHub.