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

题目:一个栈中元素的类型为整数,现在将该栈从顶到底按从大到小的顺序排序,只许申请一个栈,除此之外可以申请新的变量,但不能申请额外的数据结构。
算法思路:
将要排序的栈记为sta,申请辅助栈为st_help.保存sta栈顶元素到cur变量,并pop栈顶元素。
1)如果cur小于等于st_help栈顶元素,则将cur压入st_help
2) 如果cur小于st_help 栈顶元素,则将st_help栈顶元素压入sta,并pop st_help栈顶元素,直到cur小于等于st_help栈顶元素,然后压入cur到st_help.
3)重复 1),2),直到将所有的sta为空,然后将st_help中的元素全部压如sta.

#include <iostream>
#include <stack>
#include <string>

using namespace std;
void  SortStackByStack(stack<int> & sta)
{
    stack<int> st_help;
    int cur;
    while(!sta.empty())
    {
        cur = sta.top();
        sta.pop();
        if(st_help.empty() || cur <= st_help.top())
            st_help.push(cur);
        else {
            while(!st_help.empty() && (st_help.top() < cur))
            {
                int temp = st_help.top();
                st_help.pop();
                sta.push(temp);
            }
            st_help.push(cur);
        }
    }//first while
    while(!st_help.empty())
    {
        cur = st_help.top();
        st_help.pop();
        sta.push(cur);
    }
}

int main(void)
{
    stack<int>  st;
    int val;
    while(cin>>val)
    {
        st.push(val);
    }
    SortStackByStack(st);
    while(!st.empty())
    {
        cout <<st.top()<<" "<<endl;
        st.pop();
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值