参考 https://www.cnblogs.com/xiyuan2016/p/6830821.html
题目:
在一个栈中元素的类型为整型,现在想将该栈从栈顶到栈底按从大到小的顺序排序,只许申请一个栈,除此之外,可以申请其他变量,但是不能申请额外的数据结构 。
思路:
待排序的栈stack, 辅助栈help。 Note: 为使得 stack 栈顶到栈底元素降序,help保持 栈顶到栈底元素升序,因此 在过程中,help从栈底到栈顶是不增的。
在stack上执行pop操作,记元素为cur,
if cur <= 【help 的栈顶元素】,cur 压入help栈中;
else cur > 【help 的栈顶元素】,逐一弹出help, 直到cur <= 【help 的栈顶元素】,在将cur压入help
一直执行以上操作,直到stack中的全部元素都导入help栈中,(此时从栈顶到栈底:有小到大)
最后,将help栈中的元素逐一pop,放入stack中。
代码:
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> s;
s.push(3);
s.push(4);
s.push(5);
s.push(1);
s.push(2);
stack<int> help;
int cur;
while (!s.empty())
{
cur = s.top();
s.pop();
while (!help.empty() && help.top() < cur)
{
s.push(help.top());
help.pop();
}
help.push(cur);
}
while (!help.empty())
{
cout << help.top();
s.push(help.top());
help.pop();
}
return 0;
}