LeetCode155:Min Stack
一、题目地址:https://leetcode.com/problems/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.
Tags:Stack & Data Structure
三、代码:
class MinStack
{
stack<int> stk;
stack<int> minimum;
public:
void push(int x)
{
stk.push(x);
if(minimum.empty())
minimum.push(x);
else
if(x<=minimum.top())
minimum.push(x);
}
void pop()
{
if(stk.top()==minimum.top())
{
stk.pop();
minimum.pop();
}
else
stk.pop();
}
int top()
{
return stk.top();
}
int getMin()
{
return minimum.top();
}
};