题解 | #用递归函数和栈逆序一个栈#
用递归函数和栈逆序一个栈
http://www.nowcoder.com/practice/1de82c89cc0e43e9aa6ee8243f4dbefd
import java.util.Scanner;
import java.util.Stack;
public class CD7_用递归函数和栈逆序一个栈
{
// 递归函数一:将栈底的元素返回并移除
public static int getAndRemoveLastElement(Stack<Integer> stack)
{
// 记录位置方便递归
int x = stack.pop();
if (stack.isEmpty())
{
return x;
}
else
{
int last = getAndRemoveLastElement(stack);
stack.push(x); // 恢复原来顺序
return last;
}
}
public static void reverse(Stack<Integer> stack)
{
if (stack.isEmpty())
{
return ;
}
int x = getAndRemoveLastElement(stack);
reverse(stack);
stack.push(x);
}
public static void main(String[] args)
{
Stack<Integer> stack = new Stack<>();
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
for (int i = 1; i <= n; i++)
{
int x = scanner.nextInt();
stack.push(x);
}
reverse(stack);
while (!stack.isEmpty())
{
System.out.print(stack.pop() + " ");
}
System.out.println();
}
}