题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
import java.util.Stack;
public class Solution {
private Stack stack1;
private Stack stack2;
Solution () {
stack1 = new Stack();
stack2 = new Stack();
}
public void push(int node) {
stack1.push(node);
if(stack2.isEmpty()) {
stack2.push(node);
}else {
if(node <= (int)stack2.peek()) {
stack2.push(node);
}else {
stack2.push(stack2.peek());
}
}
}
public void pop() {
stack1.pop();
stack2.pop();
}
public int top() {
return (int)stack1.peek();
}
public int min() {
return (int)stack2.peek();
}
}