题解 | #用递归函数和栈逆序一个栈#
用递归函数和栈逆序一个栈
https://www.nowcoder.com/practice/1de82c89cc0e43e9aa6ee8243f4dbefd
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { static Stack<Integer> stack = new Stack<>(); public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = in.nextInt(); for (int i = 0; i < N; i++) { stack.add(in.nextInt()); } reverse(); while(!stack.isEmpty()) { System.out.print(stack.pop() + " "); } } //获取并移除栈底最后一个元素 public static int getAndRemoveLastElement() { int pop = stack.pop(); if (stack.isEmpty()) { return pop; }else { int last = getAndRemoveLastElement(); stack.add(pop); return last; } } //反转 public static void reverse() { if (stack.isEmpty()) { return; } int last = getAndRemoveLastElement(); reverse(); stack.add(last); } }
栈和队列,记录栈和队列的一些题 文章被收录于专栏
栈和队列,记录栈和队列的一些题