用一个栈实现另一个栈的排序

参考 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值