//
//
// 奇数在前,偶数在后,
#include <iostream>
#include <assert.h>
#include <algorithm>
#include <stack>
#include <vector>
using namespace std;
int main()
{
int an[]={4,2,5,7,12,6,12,3,21};
stack<int,vector<int> >sta1;
stack<int,vector<int> >sta2;
int i;
// 更小空间的栈
cout<<"push:"<<endl;
for (i=0; i<sizeof(an)/sizeof(int); i++)
{
sta1.push(an[i]);
if (sta2.empty())
{
sta2.push(an[i]);
}
if (an[i]>=sta2.top())
{
sta2.push(an[i]);
}
cout<<"TopA: "<<sta1.top()<<" SizeA: "<<sta1.size()<<" TopB: "<<sta2.top()<<" SizeB: "<<sta2.size()<<endl;
}
cout<<endl<<endl<<"pop: "<<endl;
while (!sta1.empty())
{
cout<<"TopA: "<<sta1.top()<<" TopB: "<<sta2.top()<<endl;
int t=sta1.top();
sta1.pop();
if (t==sta2.top())
{
sta2.pop();
}
}
return 0;
}
利用辅助堆栈。
入栈时,如果小于当前最大值,则辅助栈不动;如果大于或等于当前最大值,则辅助栈将该数push进来。
出栈时,如果top()处的数与当前最大值相同,则辅助栈也要出栈。
参考: http://www.cppblog.com/csolay/archive/2011/10/22/158858.aspx