#include<iostream>
#include<stack>
using namespace std;
#define MAX_DATA 10000000
template <class T>
class MyStack
{
stack<T> s1; //s1數據棧
stack<T> s2; //s2最小值棧
public:
void Push(const T& x)
{
T min = Min();
if (x < min)
{
s1.push(x);
s2.push(x);
}
else
{
s1.push(x);
s2.push(min);
}
}
void Pop()
{
if (!s1.empty())
{
s1.pop();
s2.pop();
}
}
T Min()
{
if (s2.empty())
{
return MAX_DATA;
}
return s2.top();
}
};
int main()
{
MyStack<int> s;
s.Push(5);
s.Push(2);
s.Push(3);
s.Push(4);
//s.Push(1);
//s.Push(6);
s.Pop();
s.Pop();
s.Pop();
int min = s.Min();
cout << "stack min = "<<min << endl;
getchar();
return 0;
}
求棧的最小值
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.