Skip to content

Commit 7f99850

Browse files
authored
feat: add indexOf, at, and print methods to LinkedList Implement three new methods for the LinkedList data structure to enhance functionality: 1. indexOf(value) - Finds and returns the index of a node with a specific value, or -1 if not found 2. at(index) - Retrieves the value at a specific index in the list, or undefined if out of bounds 3. print(callback) - Prints the entire linked list with optional formatting callback These methods address issue #2065 and provide essential utility functions for LinkedList operations. All methods follow the existing code style and include proper JSDoc documentation.
Added methods to find index of a value, get value at a specific index, and print the linked list.
1 parent 4ba97b9 commit 7f99850

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

src/data-structures/linked-list/LinkedList.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,4 +269,62 @@ export default class LinkedList {
269269

270270
return this;
271271
}
272+
273+
/**
274+
* Find the index of a node with a specific value.
275+
* @param {*} value
276+
* @return {number} Index of the node, or -1 if not found
277+
*/
278+
indexOf(value) {
279+
let index = 0;
280+
let currentNode = this.head;
281+
while (currentNode) {
282+
if (this.compare.equal(currentNode.value, value)) {
283+
return index;
284+
}
285+
currentNode = currentNode.next;
286+
index += 1;
287+
}
288+
return -1;
289+
}
290+
291+
/**
292+
* Get the value at a specific index.
293+
* @param {number} index
294+
* @return {*} The value at the specified index, or undefined if out of bounds
295+
*/
296+
at(index) {
297+
if (index < 0) {
298+
return undefined;
299+
}
300+
let currentNode = this.head;
301+
let currentIndex = 0;
302+
while (currentNode) {
303+
if (currentIndex === index) {
304+
return currentNode.value;
305+
}
306+
currentNode = currentNode.next;
307+
currentIndex += 1;
308+
}
309+
return undefined;
310+
}
311+
312+
/**
313+
* Print the entire linked list.
314+
* @param {function} callback Optional callback to format the output
315+
* @return {LinkedList}
316+
*/
317+
print(callback) {
318+
let currentNode = this.head;
319+
let result = '';
320+
while (currentNode) {
321+
result += callback ? callback(currentNode.value) : currentNode.value;
322+
currentNode = currentNode.next;
323+
if (currentNode) {
324+
result += ' -> ';
325+
}
326+
}
327+
console.log(result);
328+
return this;
329+
}
272330
}

0 commit comments

Comments
 (0)