设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
- push(x) -- 将元素 x 推入栈中。
- pop() -- 删除栈顶的元素。
- top() -- 获取栈顶元素。
- getMin() -- 检索栈中的最小元素。
解题思路:利用两个栈完成操作,第一个栈保存所有的元素,第二个栈在每个元素进入第一个栈时,保存当前最小的元素,当查询最小元素时,返回第二个栈的栈顶即可。
class Solution {
private:
stack <int> stack1, stack2;
public:
void push(int x);
void pop(void);
int top(void);
int getMin(void);
};
void Solution::push(int x)
{
#if 0
/*头插法保存元素*/
ListNode *newelement = new ListNode(x);
newelement->next = head->next;
head->next = newelement;
#endif
stack1.push(x);
if(stack2.empty() == true)
{
stack2.push(x);
}
else
{
if(x <= stack2.top())
{
stack2.push(x);
}
}
}
void Solution::pop(void)
{
#if 0
if(head->next != NULL)
{
head = head->next;
}
else
{
cout<<"stack is empty"<<endl;
}
#endif
if(stack1.empty() == true)
{
}
else
{
if(stack1.top() == stack2.top())
{
stack2.pop();
}
stack1.pop();
}
}
int Solution::top(void)
{
return stack1.top();
}
int Solution::getMin(void)
{
return stack2.top();
}