Search code examples
javascriptminimumstack

Finding min in a stack- Won't print out any result


Trying to find the min for this stack; however, whenever I run this in JSFiddle nothing prints out... anyone explain to me why? here's the code:

function min_stack() {
var min = 0; 
this.elements = [];

this.push = function(element) {
    this.elements.push(element);
}

this.pop = function() {
    return this.elements.pop();
}

this.min = function() {
    min = this.elements[0]; 
    if (this.elements.length > 0) {
        for(int i = 0; i < this.elements.length; i++) {
            if (min > this.elements[i]) {
                min = this.elements[i]; 
            }
        }
    }
    return min; 
   }    

}

var myStack = new min_stack();
myStack.push(5);
myStack.push(4);
myStack.push(3);
print("[" + myStack.elements + "]");
print("min:" + myStack.min());
myStack.pop();
print("[" + myStack.elements + "]");
print("min:" + myStack.min());
myStack.pop();
print("[" + myStack.elements + "]");
print("min:" + myStack.min());

Solution

  • There is a syntax error in your for which shows up immediately in browser console

    Change:

    for(int i = 0; i < this.elements.length; i++) { 
    

    TO

    for(var i = 0; i < this.elements.length; i++) { 
    

    DEMO: http://jsfiddle.net/y7wET/

    ALso as pointed out in comments I doubt you want to use print