-
-
Notifications
You must be signed in to change notification settings - Fork 30.6k
/
Copy pathreverseTraversal.js
34 lines (30 loc) · 885 Bytes
/
reverseTraversal.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* 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) {
// Check if the callback function is provided and is a function
if (!callback || typeof callback !== 'function') {
throw new Error('Callback function is required for reverseTraversal');
}
// Check if the linked list is empty
if (!linkedList || !linkedList.head) {
throw new Error('Cannot reverse traverse an empty linked list');
}
reverseTraversalRecursive(linkedList.head, callback);
}