定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min函数。在该栈中,调用min、push及pop的时间复杂度都是O(1)。
代码:
package offer;
import java.util.Stack;
class MinInStack
{
Stack<Integer> stack = new Stack<Integer>();
Stack<Integer> minstack = new Stack<Integer>();
MinInStack()
{
this.stack = new Stack<Integer>();
this.minstack = new Stack<Integer>();
}
boolean IsEmpty()
{
return this.stack.empty();
}
int Top()
{
return this.stack.peek();
}
int min()
{
return this.minstack.peek();
}
void Push(int val)
{
this.stack.add(val);
if(this.minstack.empty())
{
this.minstack.add(val);
}
else if(val<=this.minstack.peek())
{
this.minstack.add(val);
}
else
{
this.minstack.add(this.minstack.peek());
}
}
int Pop()
{
int x = this.stack.pop();
if(!this.minstack.empty())
{
this.minstack.pop();
}
return x;
}
}
public class ti30 {
public static void main(String[] args)
{
MinInStack stack = new MinInStack();
stack.Push(3);
System.out.println(stack.min());
stack.Push(4);
System.out.println(stack.min());
stack.Push(2);
System.out.println(stack.min());
stack.Push(1);
System.out.println(stack.min());
stack.Pop();
System.out.println(stack.min());
stack.Pop();
System.out.println(stack.min());
stack.Push(0);
System.out.println(stack.min());
}
}