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

链接:https://www.nowcoder.com/questionTerminal/ff8cba64e7894c5582deafa54cca8ff2
来源:牛客网

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

import java.util.Scanner;
import java.util.Stack;

public class Main {

    private static void sort(Stack<Integer> stack) {
        Stack<Integer> helper = new Stack<>();
        while (!stack.isEmpty()) {
            Integer pop = stack.pop();
            while (!helper.isEmpty() && helper.peek() < pop) {
                stack.push(helper.pop());
            }
            helper.push(pop);
        }

        while (!helper.isEmpty()) {
            stack.push(helper.pop());
        }
    }

    private static void print(Stack<Integer> stack) {
        StringBuilder ret = new StringBuilder();
        while (!stack.isEmpty()) {
            ret.append(stack.pop()).append(" ");
        }
        System.out.println(ret.toString().trim());
    }

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        while (in.hasNext()) {

            int n = in.nextInt();

            Stack<Integer> stack = new Stack<>();

            for (int i = 1; i <= n; ++i) {
                stack.push(in.nextInt());
            }

            sort(stack);

            print(stack);
        }

    }
}

 

上一篇:IDEA Maven Helper插件(详细使用教程)


下一篇:数据结构3