Reputation: 3293
I'm trying to write a function to find the smallest value in linkedlist using javascript. However, my code doesn't seem to work. I guess there's something wrong with the while loop. My code as follows:
function find_smallest(ll){
var i = ll;
var smallest = i.data;
while(i){
if(i.data<smallest){
smallest = i.data;
}
i.next;
}
return i.data;
}
Upvotes: 0
Views: 196
Reputation: 148
You have to return 'smallest' and not 'i.data'. That will always return the last value in the linked list.
Upvotes: 0
Reputation: 8770
Your i should now be pointing to i.next after every iteration:
function find_smallest(ll){
var i = ll;
var smallest = i.data;
while(i){
if(i.data<smallest){
smallest = i.data;
}
i = i.next;//not i.next;
}
return i.data;//i think this is smallest not i.data
}
Upvotes: 0
Reputation: 23542
What is i.next
?
A function?
i.next();
A variable?
i = i.next;
Upvotes: 0
Reputation: 230346
You most likely forgot to advance your position.
function find_smallest(ll){
var i = ll;
var smallest = i.data;
while(i) {
if(i.data < smallest){
smallest = i.data;
}
i = i.next; // <== here
}
return smallest;
}
And you have just i.next
. You need an assignment. Also, your code would raise an error in the end, because you're referring to i.data
and i
would be null
at this point.
Upvotes: 1