剑指Offer25--面试题30. 包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
代码
import java.util.Stack;
public class Solution {
Stack<Integer> stack = new Stack<>();
Stack<Integer> he = new Stack<>();
public void push(int node) {
int temp;
stack.push(node);
if(he.empty()||node<he.peek()){
he.push(node);
}
}
public void pop() {
if(!stack.empty()){
if(stack.pop().equals(he.peek())){he.pop();}
}else{
throw new RuntimeException("栈为空");
}
}
public int top() {
return stack.peek();
}
public int min() {
return he.peek();
}
}