美文网首页
用一个栈给另外一个栈排序

用一个栈给另外一个栈排序

作者: 事件_666 | 来源:发表于2019-05-29 16:30 被阅读0次

    import java.util.Stack;

    public class Problem_05_StackSortStack {

    public static void sortStackByStack(Stack<Integer> stack) {
        Stack<Integer> help = new Stack<Integer>();
        while (!stack.isEmpty()) {
            int cur = stack.pop();
    

    //核心代码
    while (!help.isEmpty() && help.peek() < cur) {
    stack.push(help.pop());
    }
    help.push(cur);
    }
    while (!help.isEmpty()) {
    stack.push(help.pop());
    }
    }

    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<Integer>();
        stack.push(3);
        stack.push(1);
        stack.push(6);
        stack.push(2);
        stack.push(5);
        stack.push(4);
        sortStackByStack(stack);
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }
    

    }

    相关文章

      网友评论

          本文标题:用一个栈给另外一个栈排序

          本文链接:https://www.haomeiwen.com/subject/huiytctx.html