剑指 Offer 第30题:包含min函数的栈
2022-07-20 本文已影响0人
放开那个BUG
1、前言

2、思路
3、代码
class MinStack {
private Stack<Integer> stack1 = new Stack<Integer>();
private Stack<Integer> stack2 = new Stack<Integer>();
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
stack1.push(x);
if(!stack2.isEmpty() && stack2.peek() < x){
return;
}
stack2.push(x);
}
public void pop() {
if(stack1.pop().equals(stack2.peek())){
stack2.pop();
}
}
public int top() {
return stack1.peek();
}
public int min() {
return stack2.peek();
}
}