面试百题066——颠倒栈

参考:http://bylijinnan.iteye.com/blog/1447035

题目:用递归颠倒一个栈。例如输入栈{1, 2, 3, 4, 5},1在栈顶。颠倒之后的栈为{5, 4, 3, 2, 1},5处在栈顶。

public void reverseStack(Stack<Integer> stack){
        if(!stack.empty()){
            Integer top=stack.pop();
            reverseStack(stack);
            addToBottom(stack,top);
        }
    }
    public void addToBottom(Stack<Integer> stack,Integer ele){
        if(stack.empty()){
            stack.push(ele);
        }else{
            Integer top=stack.pop();
            addToBottom(stack,ele);//important
            stack.push(top);
        }
    }
posted @ 2012-10-07 16:53  三块钱的其其  阅读(236)  评论(0编辑  收藏  举报