仅用递归和栈操作逆序一个栈
- 思路
通过一个递归函数获得栈最下面的元素并将其移除,最终不断获得剩余的最下面元素,再通过递归将这些元素压回去,得到一个逆序的栈。代码如下:
import java.util.*;
public class Main{
public static void main(String [] arg){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int [] arr = new int[n];
Stack<Integer> stack = new Stack();
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
for(int i=n-1; i>-1; i--){
stack.push(arr[i]);
}
Main m = new Main();
m.reverseStack(stack);
while(!stack.isEmpty()){
System.out.print(stack.pop()+" ");
}
}
public int getAndRemoveLastElement(Stack<Integer> stack){
int value = stack.pop();
if(stack.isEmpty()){
return value;
}
int last = getAndRemoveLastElement(stack);
stack.push(value);
return last;
}
public void reverseStack(Stack<Integer> stack){
if(stack.isEmpty()){
return;
}
int i = getAndRemoveLastElement(stack);
reverseStack(stack);
stack.push(i);
}
}
转载自左神程序员代码面试指南