#include <iostream>
#include <stack>
using namespace std;
template<typename T>
class Min
{
public:
void PUSH(T val)
{
T temp = val;
st1.push(val);
if (st2.empty() == true)
{
st2.push(temp);
st1.push(temp);
}
else
{
st2.pop();
while (st1.empty() == false)
{
if (st1.top() < temp)
{
temp = st1.top();
}
st2.push(st1.top());
st1.pop();
}
}
while (st2.empty() == false)
{
st1.push(st2.top());
st2.pop();
}
st2.push(temp);
}
void POP()
{
st2.pop();
if (st1.empty() == true)return;
st1.pop();
int temp = st1.top();
while (st1.empty() == false)
{
if (temp > st1.top())
{
temp = st1.top();
}
st2.push(st1.top());
st1.pop();
}
while (st2.empty() == false)
{
st1.push(st2.top());
st2.pop();
}
st2.push(temp);
}
T min()
{
if (st2.empty()==false)
return st2.top();
}
private:
stack<T> st1;
stack<T> st2;
};
int main()
{
Min<int> m;
m.PUSH(1);
m.PUSH(2);
m.PUSH(3);
m.PUSH(4);
m.PUSH(5);
m.PUSH(6);
m.PUSH(7);
m.PUSH(0);
cout << m.min() << endl;
m.POP();
cout << m.min() << endl;
m.PUSH(1);
m.PUSH(1);
m.PUSH(1);
return 0;
}
笔试题:由两个栈构造min栈
最新推荐文章于 2021-02-17 22:58:36 发布
本文介绍了一种使用两个栈来实现数据结构类Min的方法,该类能够高效地完成元素的压栈、弹栈及获取栈中最小元素的操作。通过巧妙的设计,在进行基本操作的同时能确保O(1)的时间复杂度。
1345

被折叠的 条评论
为什么被折叠?



