04-03.栈的逆序

题目

一个栈中的元素为整型,现在想将改栈从顶到低按从大到小的顺序排序,只能申请一个栈。除此之外,可以申请新的变量,但不能申请额外的数据结构,如何完成排序

代码

    public static void sortStack(Stack<Integer> stack) {
        Stack<Integer> help = new Stack<>();
        while (!stack.isEmpty()) {
            int currentNum = stack.pop();
            while (!help.isEmpty() && help.peek() > currentNum) {
                stack.push(help.pop());
            }
            help.push(currentNum);
        }
        while (!help.isEmpty()) {
            stack.push(help.pop());
        }
    }
发布了99 篇原创文章 · 获赞 72 · 访问量 54万+

猜你喜欢

转载自blog.csdn.net/wj123446/article/details/105047330