【题目】在不借助其他数据结构的情况下,逆序栈
public class ReverseStackUsingRecursive {
private static void reverse(Stack stack){
if (stack.isEmpty()){
return;
}
int i = getAndRemoveLastElement(stack);
reverse(stack);
stack.push(i);
}
private static int getAndRemoveLastElement(Stack stack) {
Integer pop = stack.pop();
if (stack.isEmpty()){
return pop;
} else {
int last = getAndRemoveLastElement(stack);
stack.push(pop);
return last;
}
}
public static void main(String[] args) {
Stack stack = new Stack<>();
pushStack(stack, 5);
printStack(stack);
pushStack(stack, 5);
reverse(stack);
System.out.println("转换后");
printStack(stack);
}
private static void pushStack(Stack stack, int n){
for (int i = 1; i <= n; i++) {
stack.add(i);
}
}
private static void printStack(Stack stack) {
while (!stack.isEmpty()){
System.out.print(stack.pop()+", ");
}
}
}



