新手练手感--part1.1 栈与队列之用一个栈实现另一个栈的排序

题目:

  给你一个栈,里面若干元素,只能在额外申请一个栈,请实现栈顶到栈底的排序问题

思路:

(1)一个栈stack,另一个栈help

(2)int a = stack.pop(),help.empty||a > help.peek,直接helo.put(a)

(3)a < help.peek(),则help.pop, stack.push,直到a >= help.peek()

public class TestCode {


    public static void main(String[] args) {
        //存放栈数据
        Stack<Integer> stack = new Stack<Integer>();
        for(int i = 0; i < 10; i++) {
            stack.push((int)(Math.random() * 10));
        }
        Stack<Integer> help = new Stack<Integer>();
        while(!stack.isEmpty()) {
            int num = stack.pop();
            if(help.isEmpty() ||num >= help.peek() ) {
                help.push(num);
            } else {
                //在help栈顶比num大时,弹出help中元素,压入stack中
                while(!help.isEmpty() && help.peek() > num) {
                    stack.push(help.pop());
                }
                help.push(num);
            }
        }

        while(!help.isEmpty()) {
            stack.push(help.pop());
            System.out.print("  " + stack.peek());
        }
    }

}

 

posted @ 2017-06-08 02:00  jiguojing  阅读(236)  评论(0编辑  收藏  举报