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

【题目】

一个栈中元素类型为整型,想将该栈从顶到底按从大到小排序,只允许申请一个栈。除此之外,可以申请新变量,但不能申请额外的数据结构。

【举例】

    public static void main(String[] args) {
        Stack<Integer> ms=new Stack<Integer>();
        ms.push(3);
        ms.push(4);
        ms.push(5);
        ms.push(1);
        ms.push(2);

        sortStack(ms);
        System.out.println(ms.pop());//5
        System.out.println(ms.pop());//4
        System.out.println(ms.pop());//3
        System.out.println(ms.pop());//2
        System.out.println(ms.pop());//1
    }

【代码】

//用一个栈实现另一个栈的排序
    public static void sortStack(Stack<Integer> stack){
        Stack<Integer> help=new Stack<Integer>();
        while(!stack.isEmpty()){
            int cur=stack.pop();//已将cur弹出,准备压入help
            while(!help.isEmpty()&&cur>help.peek()){
                stack.push(help.pop());
                //如果cur大于Help栈顶元素,将help元素逐一弹出、逐一压入stack
                //直到cur小于或等于help栈顶元素,再将cur压入help
            }
            help.push(cur);//栈顶元素最小,cur≤栈顶,直接压入Help
        }
        //到这里为止,stack所有元素都弹出了
        while(!help.isEmpty()){
            stack.push(help.pop());//只要help不为空,将排好序的元素逐一弹出、压入到stack
        }
    }

【疑惑】
从结果来看,最后似乎是从顶到底按从小到大的顺序排列的?

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值