From 7f9985042e98fdf2b03d7e14d37d1e4931a37f12 Mon Sep 17 00:00:00 2001 From: Tamalampudi Siva Harsha Vardhan Reddy <2400030361@kluniversity.in> Date: Mon, 24 Nov 2025 19:05:11 +0530 Subject: [PATCH] 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. --- src/data-structures/linked-list/LinkedList.js | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/src/data-structures/linked-list/LinkedList.js b/src/data-structures/linked-list/LinkedList.js index ba7d0e3ee..83374d94b 100644 --- a/src/data-structures/linked-list/LinkedList.js +++ b/src/data-structures/linked-list/LinkedList.js @@ -269,4 +269,62 @@ export default class LinkedList { return this; } + + /** + * Find the index of a node with a specific value. + * @param {*} value + * @return {number} Index of the node, or -1 if not found + */ + indexOf(value) { + let index = 0; + let currentNode = this.head; + while (currentNode) { + if (this.compare.equal(currentNode.value, value)) { + return index; + } + currentNode = currentNode.next; + index += 1; + } + return -1; + } + + /** + * Get the value at a specific index. + * @param {number} index + * @return {*} The value at the specified index, or undefined if out of bounds + */ + at(index) { + if (index < 0) { + return undefined; + } + let currentNode = this.head; + let currentIndex = 0; + while (currentNode) { + if (currentIndex === index) { + return currentNode.value; + } + currentNode = currentNode.next; + currentIndex += 1; + } + return undefined; + } + + /** + * Print the entire linked list. + * @param {function} callback Optional callback to format the output + * @return {LinkedList} + */ + print(callback) { + let currentNode = this.head; + let result = ''; + while (currentNode) { + result += callback ? callback(currentNode.value) : currentNode.value; + currentNode = currentNode.next; + if (currentNode) { + result += ' -> '; + } + } + console.log(result); + return this; + } }