1.第一个函数 找到返回并删除栈最底层的元素
2.第二个函数 拿到元素 利用递归 在逆序压入栈
import java.util.Stack;
public class ReverseStack {
public static int floorNumber(Stack<Integer> stack){
int num = stack.pop();
if(stack.empty()){
return num;
}else{
int last = floorNumber(stack);
stack.push(num);
return last;
}
}
public static void reverseStackRecursively(Stack<Integer> stack) {
if(stack.empty()){
return ;
}
int i = floorNumber(stack);
reverseStackRecursively(stack);
stack.push(i);
}
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
reverseStackRecursively(stack);
while (!stack.empty()){
System.out.print(stack.pop());;
}
}
}
画了个图解释一下第一个函数
第二个函数的话就很好理解了 不会的话可以参考上一个图画一画~~~
补一下后续
牛客上有一道这个题:然后他要输入输出 代码main里浅修一下
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
while(scanner.hasNext()){
stack.push(scanner.nextInt());
}
reverseStackRecursively(stack);
while(!stack.empty()){
System.out.print(stack.pop()+" ");
}
}
啊嘞 题目掉落 快去刷!!!!!!! CD7 用递归函数和栈逆序一个栈