Created
March 22, 2013 03:24
-
-
Save Gankra/5218710 to your computer and use it in GitHub Desktop.
MinStack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function MinStack(){ | |
this.stack = []; | |
this.min = []; | |
} | |
MinStack.prototype.push = function(x){ | |
if(this.stack.length==0){ | |
this.min.push(x); | |
}else{ | |
if(this.getMin()>x){ | |
this.min.push(x); | |
}else{ | |
this.min.push(this.getMin()); | |
} | |
} | |
this.stack.push(x); | |
} | |
MinStack.prototype.pop = function(){ | |
this.min.pop(); | |
return this.stack.pop(); | |
} | |
MinStack.prototype.getMin = function(){ | |
return this.min[this.min.length-1]; | |
} | |
var stack = new MinStack(); | |
stack.push(3); | |
stack.push(5); | |
console.log(stack.getMin()); | |
stack.push(4); | |
console.log(stack.getMin()); | |
stack.push(1); | |
console.log(stack.getMin()); | |
stack.pop(); | |
console.log(stack.getMin()); | |
stack.pop(); | |
console.log(stack.getMin()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment