方法:
- 如果help为空,或者s.top()小于help.top(),将s的栈顶压入help中
- 如果s.top()大于help.top(),保存下s.top()为temp,将help的栈顶依次压入s中,直到help为空或者help的栈顶小于temp。然后把temp压入help。
- 重复上述步骤直到s为空
- 将help的元素全部弹出压入s中,得到s从栈底到栈顶的升序排列。
s从栈底到栈顶升序排列 就要求 help从栈底到栈顶降序排列,即s.top() < help.top() 就往里放
简而言之:原栈顶小则往辅助栈中放,大则保持help次序不变(依次放如原栈中),到了点就插入(插入help中)。
代码:
#include<unordered_map>
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main()
{
stack<int> s;
stack<int> help;
s.push(1);
s.push(12);
s.push(31);
s.push(13);
s.push(5);
while(!s.empty())
{
if(help.empty()||s.top()<=help.top())
{
help.push(s.top());
s.pop();
}
else if(s.top()>help.top())
{
int temp=s.top();
s.pop();
while(!help.empty()&&temp>help.top())
{
s.push(help.top());
help.pop();
}
help.push(temp);
}
}
while(!help.empty())
{
s.push(help.top());
help.pop();
}
while(!s.empty())
{
cout<<s.top()<<endl;
help.pop();
}
}