思路就是:每次从利用递归,从栈中取出栈底元素,然后将其他元素按原来的顺序压入栈中即可。
import java.util.Stack;
import java.util.Scanner;
public class Main {
public static int getAndRemoveLastElement(Stack<Integer> stack) {
int result = stack.pop();
if (stack.isEmpty()) {
return result;
} else {
int last = getAndRemoveLastElement(stack);
stack.push(result);
return last;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
Stack<Integer> stack = new Stack<>();
int[] nums = new int[num];
for (int i = 0; i < num; i++) {
nums[i] = sc.nextInt();
}
for (int i = num - 1; i>= 0; i--){
stack.push(nums[i]);
}
for (int i = 0; i < num; i++) {
int result = getAndRemoveLastElement(stack);
System.out.print(result + " ");
}
}
}
这里增加了reverse函数,真正达到了逆序栈的效果,这里调用了之前的getAndRemoveLastElement函数。
import java.util.Stack;
import java.util.Scanner;
public class Main{
public static int getAndRemoveElement(Stack<Integer> stack){
int result = stack.pop();
if (stack.isEmpty()) {
return result;
} else {
int last = getAndRemoveElement(stack);
stack.push(result);
return last;
}
}
public static void reverse(Stack<Integer> stack){
if (stack.isEmpty()) {
return;
}
int i = getAndRemoveElement(stack);
reverse(stack);
stack.push(i);
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int elementNum = sc.nextInt();
Stack<Integer> stack = new Stack<>();
int[] element = new int[elementNum];
for (int i = 0; i < elementNum; i++) {
element[i] = sc.nextInt();
}
for (int i = elementNum - 1; i >= 0; i--) {
stack.push(element[i]);
}
reverse(stack);
while(!stack.isEmpty()){
System.out.print(stack.pop() + " ");
}
}
}