定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数。
- 参考
牛客网-《剑指offer_编程题》
- 思路
应用一个辅助栈。
压栈:如果A栈的压入比B栈压入大,B栈不压,小于等于时,AB栈同时压入。
出栈:如果AB栈顶元素不等,A出,B不出。
- 代码
public class Solution {
private Stack<Integer> stackData = new Stack<>();
private Stack<Integer> stackMin = new Stack<>();
public void push(int node) {
stackData.push(node);
if(stackMin.empty()){
stackMin.push(node);
}else if(node<= stackMin.peek()){
stackMin.push(node);
}
}
public void pop() {
if(stackData.isEmpty()){
throw new RuntimeException("The Stack is Empty!");
}
if(stackData.peek() == stackMin.peek()){
stackMin.pop();
}
stackData.pop();
}
public int top() {
if(stackData.isEmpty()){
throw new RuntimeException("The Stack is Empty!");
}
int value = stackData.pop();
if(value == stackMin.peek()){
stackMin.peek();
}
return value;
}
public int min() {
if(stackMin.isEmpty()){
throw new RuntimeException("The Stack is Empty!");
}
return stackMin.peek();
}
}
网友评论