首页 > 解决方案 > 创建一个包含以下数字的列表(递归)

问题描述

我需要该函数返回一个包含以下数字的列表,所以follow(null, 5);应该返回[1, 2, 3, 4, 5]

我试过这个:

public static Node <Integer> follow(Node<Integer>list, int num)
{
    if(num==1)
        return new Node<Integer>(1);
    return new Node<Integer>(num, follow(list, num-1));
}

但这会返回[5, 4, 3, 2, 1]而不是[1, 2, 3, 4, 5]我需要在函数中更改什么以便返回[1, 2, 3, 4, 5]?(我不想添加其他功能)

这是节点类:

package unit4.collectionsLib;

public class Node<T>
{
    private T info;
    private Node<T> next;

    public Node(T x)
    {
        this.info = x;
        this.next = null;
    }

    public Node(T x, Node<T> next)
    {
        this.info = x;
        this.next = next;
    }

    public T getValue()
    {
        return(this.info);
    }



}

标签: javalistrecursionnodes

解决方案


随着您深入递归,您正在从 5 倒数到 1。如果在深入递归的过程中从 1 数到 5 会怎样?数字的顺序是什么?

为了实现这一点,最大数量(在您的示例中为 5)需要在每个递归步骤中都可用,因此您需要一个额外的参数。

public static Node <Integer> follow(Node<Integer>list, int num, int max)
{
    if(num==max)
        return new Node<Integer>(max);
    return new Node<Integer>(num, follow(list, num + 1, max));
}

如果您仍然希望在不传递额外参数的情况下方便地调用,您可以通过添加它的方便版本来重载该方法:

public static Node <Integer> follow(Node<Integer>list, int max)
{
    return follow(list, 1, max);
}

推荐阅读