Min Stack
要求
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.
标签:Stack, Data Structure
我的提交:
public class MinStack {
Stack<int> stack;
Stack<int> minStack;
public MinStack()
{
stack = new Stack<int>();
minStack = new Stack<int>();
}
public void Push(int x) {
stack.Push(x);
if (minStack.Count == 0)
minStack.Push(x);
else if(minStack.Peek() >= x)
minStack.Push(x);
}
public void Pop() {
if(stack!=null)
{
int ele = stack.Pop();
if (ele == minStack.Peek())
minStack.Pop();
}
}
public int Top() {
return stack.Peek();
}
public int GetMin() {
return minStack.Peek();
}
}
注意事项:
- 使用两个栈,1st栈正常使用,2nd栈为最小栈,当新加入的元素值elem小于等于正常栈栈顶元素时,elem压入正常栈同时压入最小栈
- 对于最小栈,栈为空时(初始状态),新元素elem必加入栈中
P.S:欢迎各位学友都对我的解法的不足之处作出建议!