#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;
}
设计栈并获取最小值
最新推荐文章于 2022-01-20 16:02:54 发布
本文介绍了一个使用两个栈实现的C++数据结构,该结构支持push、pop和getMin操作,且所有操作的时间复杂度均为O(1)。通过维护一个额外的栈来保存最小值,当新元素小于当前最小值时,将其存入最小值栈。在弹出元素时,如果弹出的元素等于最小值栈顶元素,同时将其从最小值栈中移除。这个设计确保了在常数时间内获取栈中的最小值。
摘要由CSDN通过智能技术生成