注:只能用递归实现
import java.util.Stack;
//用递归逆序栈中元素
public class Problems_01 {
public static void reserve(Stack<Integer> stack){
if(stack.isEmpty()){
return;
}
//获得栈底元素
int i=getP(stack);
reserve(stack);
stack.push(i);
}
public static int getP(Stack<Integer> stack){
int result=stack.pop();
if(stack.isEmpty()){
return result;
}
int last=getP(stack);
stack.push(result);
return last;
}
public static void main(String []args){
Stack<Integer> stack=new Stack<Integer>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
reserve(stack);
while(!stack.isEmpty()){
System.out.print(stack.pop()+" ");
}
}
}