0

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;
}
qiao
  • 17,941
  • 6
  • 57
  • 46
Jia-Luo
  • 3,023
  • 5
  • 16
  • 17
  • 3
    just as a matter of practicality -- you're setting yourself up for failure by naming your parameter "ll". The font makes it look like "eleven". – Daniel Szabo Jan 18 '12 at 08:24
  • http://stackoverflow.com/a/1669222/871580 Have a look at this. You might need to convert data using a method such as Array.prototype.slice.call(data, 0) to convert data to an array. – CBusBus Jan 18 '12 at 08:28

4 Answers4

1

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.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
0

What is i.next?

A function?

i.next();

A variable?

i = i.next;
PiTheNumber
  • 22,828
  • 17
  • 107
  • 180
0

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
}
jerjer
  • 8,694
  • 30
  • 36
0

You have to return 'smallest' and not 'i.data'. That will always return the last value in the linked list.

sure_render
  • 148
  • 2
  • 7