66.颠倒栈(栈)。
题目:用递归颠倒一个栈。例如输入栈{1, 2, 3, 4, 5},1在栈顶。
颠倒之后的栈为{5, 4, 3, 2, 1},5处在栈顶。
package com.algo.ms;
import java.util.Stack;
public class ReverseStack66 {
public void reverse(Stack res){
if(!res.empty()) {
int ele = (int) res.pop();
this.reverse(res);
this.addToBottom(res, ele);
}
}
public void addToBottom(Stack res, int ele){
if(res.empty()){
res.push(ele);
} else {
int top = (int) res.pop();
this.addToBottom(res, ele);
res.push(top);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack res = new Stack();
res.push(1);
res.push(2);
res.push(3);
res.push(4);
res.push(5);
ReverseStack66 stack = new ReverseStack66();
stack.reverse(res);
System.out.println(res.peek());
}
}