题解 | #CD7 用递归函数和栈逆序一个栈#
用递归函数和栈逆序一个栈
http://www.nowcoder.com/practice/1de82c89cc0e43e9aa6ee8243f4dbefd
- 运行时间:100ms,超过84.68% 用Java提交的代码
- 占用内存:13776KB,超过84.47%用Java提交的代码
import java.util.*;
import java.io.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) throws IOException {
Main mn = new Main();
BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
int row = Integer.parseInt(sc.readLine());
Deque<Integer> stack = new LinkedList<>();
String sn = sc.readLine();
String[] ss = sn.split(" ");
for(String s : ss) {
stack.push(Integer.valueOf(s));
}
reverse(stack);
while(!stack.isEmpty()){
System.out.print(stack.pop() + " ");
}
}
public static void reverse(Deque<Integer> stack) {
if(stack.isEmpty()) return;
int last = getAndRemoveLast(stack);
reverse(stack);
stack.push(last);
}
public static int getAndRemoveLast(Deque<Integer> stack) {
int num = stack.pop();
if(stack.isEmpty()) return num;
int last = getAndRemoveLast(stack);
stack.push(num);
return last;
}
}