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

  一个栈中的元素都是整形,现在想要将该栈从顶到底按从大到小的顺序排序,只许申请一个栈。除此之外,可以申请新的变量,但是不能申请额外的数据结构。如何实现排序?

import java.util.Stack;
public class SortStackByStack {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(2);
        stack.push(1);
        stack.push(3);
        stack.push(-1);
        stack.push(100);
        stack.push(8);
        stack = sortStackByStack(stack);
        while (!stack.isEmpty()){
            System.out.print(stack.pop() + " ");
        }
    }
    private static  Stack<Integer> sortStackByStack(Stack<Integer> stack){
        Stack<Integer> help = new Stack<>();
        while (!stack.isEmpty()){
            int cur = stack.pop();
            while (!help.isEmpty() &&  help.peek() < cur){
                //1.将help中更小的数先压回stack中,下次再压回来
                stack.push(help.pop());
            }
            //2.help压入当前的值
            help.push(cur);
        }
        while (!help.isEmpty()){
            stack.push(help.pop());
        }
        return stack;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值