xamples
epeat
ode
pproach
ptimize
est
Recall that a stack is a last in first out data structure– data is always added to and removed from the top.
You need to implement a Stack data structure that has the following functions
All of the above functions should run in constant ( O(1) ) time.
No arrays or array methods should be used.
Idea: have a separate structure that keeps track of the minimum for each node added. when you remove a node, remove the minimum that corresponds
Stack
Min
6
6
Stack
Min
6
6
7
6
Stack
Min
6
6
7
6
3
3
Stack
Min
6
6
7
6
3
3
2
2
Stack
Min
6
6
7
6
3
3
Stack
Min
6
6
7
6
Stack
Min
6
6
function Stack() {
this.top = null;
}
Stack.prototype.minimum = function() {
return this.minStack.peek();
}
Stack.prototype.push = function(val) {
var newNode = new Node(val);
if (!this.top) {
this.top = newNode;
this.minStack = new Stack();
this.minStack.push(val);
return;
}
newNode.next = this.top;
this.top = newNode;
if (this.minimum() > val)
this.minStack.push(val);
else
this.minStack.push(this.minimum());
};
Stack.prototype.pop = function() {
if (!this.top) return null;
var popped = this.top.val;
this.top = this.top.next;
if (this.minStack)
this.minStack.pop();
return popped;
};
Stack.prototype.peek = function() {
if (!this.top) return null;
return this.top.val;
};
function Node(val,next) {
this.val = val;
this.next = next;
}
function Stack() {
this.top = null;
}
Stack.prototype.push = function(val) {
var newNode = new Node(val);
if (!this.top) {
this.top = newNode;
return;
}
newNode.next = this.top;
this.top = newNode;
};
Stack.prototype.pop = function() {
if (!this.top) return null;
var popped = this.top.val;
this.top = this.top.next;
return popped;
};
Stack.prototype.peek = function() {
if (!this.top) return null;
return this.top.val;
};
function Node(val,next) {
this.val = val;
this.next = next;
}
function MinStack() {
Stack.call(this);
this.minStack = new Stack();
}
MinStack.prototype.push = function(val) {
var newNode = new Node(val);
if (!this.top) {
this.top = newNode;
this.minStack.push(val);
return;
}
newNode.next = this.top;
this.top = newNode;
if (this.minStack.peek() > val)
this.minStack.push(val);
}
MinStack.prototype.pop = function() {
if (!this.top) return null;
var popped = this.top.val;
if (this.minStack.peek() === popped)
this.minStack.pop();
this.top = this.top.next;
return popped;
}
MinStack.prototype.min = function() {
return this.minStack.peek();
}