java - 创建一个包含以下数字的列表(递归)
问题描述
我需要该函数返回一个包含以下数字的列表,所以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);
}
}
解决方案
随着您深入递归,您正在从 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);
}
推荐阅读
- r - 基于部分字符串匹配比较两个数据帧的两列
- c - 尝试在 C 中创建基本套接字连接并在 accept() 上运行到无限循环
- excel - 从 excel 宏更改 word doc 中的链接
- asp.net-core - 将带有列表的 JSON 发送到控制器
- svg - 如何旋转svg圆
- docker - 在 docker build 中连接到 dotnet.testcontainer 失败并显示消息“无法分配请求的地址 /var/run/docker.sock”
- r - 在 R 中满足条件时跳过一行代码
- java - openjfx javafxplugin jar创建中的多个服务文件冲突
- javascript - 不了解递归的下一次迭代
- tableau-api - 处理变化数据的“Tableau”方式是什么?