面试百题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); } }