递归解法
题 解 见 注 解
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
//==================核心代码=========================
static int[] stk = new int[2000]; //模拟栈
static int tt = -1; //栈顶指针
//reverse()
static void reverse() {
if (tt < 0) { //如果栈是空的,根本不用鸟
return;
}
int val = getAndremoveLastNum(); //1 我拿到并删除栈底的元素
reverse(); //2 然后把剩下的元素逆置 (我管你怎么逆置,反正你reverse()就是能逆置)
stk[++ tt] = val; //3 再讲刚才的拿的栈底元素放大栈顶
//==> 这不就逆置整个栈了嘛
}
//getAndremoveLastNum()
static int getAndremoveLastNum() {
int tmp = stk[tt --]; //我先把栈顶元素拿出来
if (tt < 0) { //要是拿完后栈就空了,那刚好我拿的就是栈底元素
return tmp; //那就直接ok,把值返回
}
//否则的话,那我就用这种方式拿栈底元素
int last = getAndremoveLastNum(); //我管你,反正你getAndremoveLastNum()就是能拿栈底元素
stk[++ tt] = tmp; //栈底的元素我拿到了,那刚开始从栈顶拿的就给人放回栈顶去
return last; //送栈底值上路
}
//============================================================
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(reader.readLine());
String[] str = reader.readLine().split(" ");
reader.close();
for (int i = 0; i < N; i ++ ) {
stk[++ tt] = Integer.parseInt(str[i]);
}
reverse();
StringBuilder res = new StringBuilder();
while(tt >= 0){
res.append(stk[tt --]).append(" ");
}
System.out.println(res);
}
}