Skip to content

Instantly share code, notes, and snippets.

@Gankra
Created March 22, 2013 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gankra/5218710 to your computer and use it in GitHub Desktop.
Save Gankra/5218710 to your computer and use it in GitHub Desktop.
MinStack
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