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

2019-02-15  本文已影响0人  上杉丶零

【题目】

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

package algorithm_and_data_structure.stack_and_queue;

import java.util.Stack;

public class SortStackByStack {
    public static void sortStackByStack(Stack<Integer> stack) {
        Stack<Integer> help = new Stack<Integer>();

        while (!stack.isEmpty()) {
            int cur = stack.pop();

            while (!help.isEmpty() && cur > help.peek()) {
                stack.push(help.pop());
            }

            help.push(cur);
        }

        while (!help.isEmpty()) {
            stack.push(help.pop());
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读