- java
可以用数组和ArrayList两种实现
我们选择了较为简单的ArrayList来实现
class MinStack {
/** initialize your data structure here. */
List<Integer> list=new ArrayList<>();
public MinStack() {
}
public void push(int x) {
list.add(x);
}
public void pop() {
list.remove(list.size()-1);
}
public int top() {
return list.get(list.size()-1);
}
public int getMin() {
int min=list.get(0);
for(int num:list){
if(num<min)
min=num;
}
return min;
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
- javascript
javascript中使用引用类型Array实现
/**
* initialize your data structure here.
*/
var MinStack = function() {
//对于原型模式而言,引用类型的属性会被所有实例共享,因此使用构造函数模式来定义list。
this.list=new Array();
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.list.push(x);
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
this.list.pop();
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.list[this.list.length-1];
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
let min=this.list[0];
for(let i=1;i<this.list.length;i++){
if(this.list[i]<min)
min=this.list[i];
}
return min;
};
/**
* Your MinStack object will be instantiated and called as such:
* var obj = Object.create(MinStack).createNew()
* obj.push(x)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.getMin()
*/