#include <iostream>
#include <stack>
using namespace std;
/*实现一个栈,该栈带有出栈(pop)、入栈(push)、取最小元素 (getMin)3个方法。
要保证这3个方法的时间复杂度都是O(1)。
两个栈对象A和B, A用于存储所有数据,A对象默认第一个元素为最小值,B用于存储A中的最小值
若B中top的值比新待插入元素大,则将新插入元素插入到B中;
A执行pop时,先A中top值与B中top值相等,则也删除B中top值;
*/
template<class T>
class CMyStack{
public:
CMyStack(){};
~CMyStack(){};
T getMin()
{
return this->min.top();
}
int push(const T& item)
{
if (all.empty())
{
this->all.push(item);
this->min.push(item);
return 0;
}
T curr_min = getMin();
if (curr_min > item)
{
this->min.push(item);
}
this->all.push(item);
return 0;
}
int pop()
{
T curr_value = all.top();
T curr_min = min.top();
this->all.pop();
if (curr_value == curr_min)
{
this->min.pop();
}
return 0;
}
private:
stack<T> all;
stack<T> min;//用于存储最小值
};
int main()
{
CMyStack<int> sk;
sk.push(20);
cout<<sk.getMin()<<endl;
sk.push(10);
cout<<sk.getMin()<<endl;
sk.push(30);
cout<<sk.getMin()<<endl;
sk.push(20);
cout<<sk.getMin()<<endl;
return 0;
}
设计栈并获取最小值
最新推荐文章于 2021-12-22 22:53:01 发布