题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
import java.util.Stack;
public class Solution {
Stack<Integer> s=new Stack<Integer>();
Stack<Integer> m=new Stack<Integer>();
public void push(int node) throws Exception{
if(m.empty())
m.push(node);
else if(node<m.peek())
m.push(node);
s.push(node);
}
public void pop() throws Exception{
if(s.peek()==m.peek())
{
s.pop();
m.pop();
}
else
s.pop();
}
public int top() throws Exception{
return s.peek();
}
public int min() throws Exception{
return m.peek();
}
}
数字栈+辅助栈
特别注意当辅助栈为空时一定会向其中压入数据
Stack类的四个方法:peek() empty() pop() push()