educative.io

Educative

Searched Linked List

Data Structures in JavaScript: Visualizations & Exercises

Let’s do an exercise. We now want to implement the search in a linked list. Search function takes in a value and either returns the index of the node if the value exists or returns null if value doesn’t exist in the linked list.

LinkedList.prototype.search = function(data) {
/////// TODO ///////
////// IMPLEMENT THIS /////
////// RUN AFTER IMPLEMENTING THIS /////
////// TESTS SHOULD PASS /////
var current = this._head;
var counter = 0;
while(current !== null) {
if(current.data == data ){
return counter;
}
current = current.next;
}
return null;
}

// This is the function that runs test cases.
runEvaluation();

could you please help me to understand where I am doing wrong

Hi @nirmalgit,

Normally, in a LinkedList, we normally return the pointer of the node where we found the value. For this, you can simply use return current instead of return counter.

But, if we want to return the index or the position of the value, just increment the counter where we are forwarding the current pointer. Add a counter++ statement that will increment the counter value as we move our pointer to the next position.

Please let me know if you have any further queries.
Thanks.