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

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

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 江苏

相关推荐

06-01 21:50
已编辑
天津理工大学 Java
点赞 评论 收藏
分享
06-26 17:24
已编辑
宁波大学 golang
迷失西雅图:别给,纯kpi,别问我为什么知道
点赞 评论 收藏
分享
评论
5
收藏
分享

创作者周榜

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