题解 | #用递归函数和栈逆序一个栈#

用递归函数和栈逆序一个栈

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();
    }
}

全部评论
哪家啊
点赞 回复 分享
发布于 2023-12-14 09:17 江苏
哪家啊
点赞 回复 分享
发布于 2023-12-13 19:09 江苏

相关推荐

不愿透露姓名的神秘牛友
07-08 13:05
点赞 评论 收藏
分享
06-22 10:41
赣东学院 Java
程序员小白条:?周六晚上投,这是什么操作,专门找996起步的吗
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 15:58
点赞 评论 收藏
分享
评论
5
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务