
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.
//vs2012测试代码
//相比传统stack(记为stk),为了记录最小值,需要再开一个最小值栈min。
//需要注意的是:重复出现的最小值必须重复进min,不然出stk的时候,min可能会为空出错
#include<iostream>
#include<stack>
using namespace std;
class MinStack {
stack<int> min;
stack<int> temp;
public:
void push(int x)
{
temp.push(x);
if( min.empty() || x<=min.top() )
min.push(x);
}
void pop()
{
if( temp.top()==min.top() )
{
temp.pop();
min.pop();
}
else
temp.pop();
}
int top()
{
return temp.top();
}
int getMin()
{
return min.top();
}
};
int main()
{
MinStack lin;
for(int i=0; i<5; i++)
{
int x;
cin>>x;
lin.push(x);
}
cout<<lin.getMin()<<endl;
}//方法一:自测Accepted
//相比传统stack(记为stk),为了记录最小值,需要再开一个最小值栈min。
//需要注意的是:重复出现的最小值必须重复进min,不然出stk的时候,min可能会为空出错
class MinStack {
stack<int> min;
stack<int> temp;
public:
void push(int x)
{
temp.push(x);
if( min.empty() || x<=min.top() )
min.push(x);
}
void pop()
{
if( temp.top()==min.top() )
{
temp.pop();
min.pop();
}
else
temp.pop();
}
int top()
{
return temp.top();
}
int getMin()
{
return min.top();
}
};原文地址:http://blog.csdn.net/keyyuanxin/article/details/43699585