最小栈
1.题目
2.画图分析
3.代码实现
java
package Stack;
import java.util.Stack;
public class MinStack {
private Stack <Integer> stack;
private Stack <Integer> MinStack;
public MinStack() {
stack = new Stack<>();
MinStack = new Stack<>();
}
public void push(int val) {
//普通栈只要是元素都得放
//最小栈 如果为空,放元素.如果不为空且要放的元素比栈顶元素小,也要放
stack.push(val);
if(MinStack.empty()){
MinStack.push(val);
}
else{
int peek = MinStack.peek();
if(val <= peek){
MinStack.push(val);
}
}
}
public void pop() {
int val = stack.pop();
//如果最小栈不为空
if(!MinStack.empty()){
if(val == MinStack.peek()){
MinStack.pop();
}
}
}
//获取普通栈的栈顶
public int top() {
return stack.peek();
}
public int getMin() {
if(!MinStack.empty()){
return MinStack.peek();
}
return -1;
}
}