【发布时间】:2020-03-22 09:50:58
【问题描述】:
我需要该函数返回一个包含以下数字的列表,所以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);
}
}
【问题讨论】:
-
您不需要我们的帮助,您已经拥有所需的所有信息。查看您的代码:为什么将较小的数字放在较高数字的右侧而不是左侧? (拿一支铅笔和一些纸,从字面上写出当你从 num=2 开始时每一步发生的事情)
-
Node的构造函数是什么? -
补充迈克的评论:问题在于你的递归顺序。
-
我无法理解如何订购,这令人困惑。
-
你仍然可以使用相同的实现然后反转它的顺序,如果它是一个数组。