我的节点构造函数如下所示:
public Node(int ndata, Node nlink)
{
this.data=ndata;
this.link = nlink;
}
这个构造函数有两个参数,节点的数据和到下一个节点的链接。然而,对于我所看到的创建链表的所有内容,都会创建一个新节点,如下所示:
节点 nextNode = 新节点(数据);
但是,如果由于某种原因我没有将第二个参数放入程序中,我将无法运行该程序。这是我的代码。
public static Node ListGenerator()
{
// Generate RANDOM List
int j, cint, size;
Scanner input = new Scanner(System.in);
System.out.println("Please enter the size");
size = input.nextInt();
//Node head;
Node current = null;
for (j = 1; j <= size; j++) {
cint = (int)((Math.random() * 100)+1);
Node nextNode = new Node (cint,current.getLink());
current = nextNode;
} return current;
// ...
}
我是链表新手,所以这对我来说非常困惑,即使这可能是我没有得到的非常简单的事情。
最佳答案
在您的代码中需要考虑以下几点:
您需要一个
head
除了current
之外的变量最终返回给调用者(这已被注释掉,所以你走在正确的轨道上)。您第一次调用
current.getLink()
会崩溃,因为current
开头为null
.此构造函数对于
Node
是正常的。 。您可以通过null
进入第二个参数作为下一个节点的临时占位符,假设您有一个供以后使用的 setter。您可能希望重载构造函数以支持link
作为可选参数,但如果您无权编辑该类,则没有必要。添加
Scanner
里面ListGenerator
不必要地将其使用仅限于用户输入。这个 I/O 逻辑最好放在你的main
中。方法(或任何调用范围)。进一步沿着这些思路,考虑传入节点值数组并将随机数生成移出该方法,进一步提高模块化/可重用性。Java 中的方法名称应采用小驼峰命名法。
方法顶部的 ANSI C 风格变量声明,如
int j, cint, size;
Java中一般不使用;最好在循环范围内声明索引变量。
这是一种从列表末尾开始并使用两个指向 head
的指针向前推进的方法。以及紧随其后的节点 next
,即null
在第一次迭代时:
class Node {
public int data;
public Node link;
public Node(int data, Node link) {
this.data = data;
this.link = link;
}
}
class Main {
public static Node listGenerator(int size) {
Node next = null;
Node head = null;
for (int i = 1; i < size; i++) {
head = new Node((int)(Math.random() * 100) + 1, next);
next = head;
head = null;
}
head = new Node((int)(Math.random() * 100) + 1, next);
return head;
}
public static void main(String[] args) {
Node head = listGenerator(6);
while (head != null) {
System.out.print(head.data + "->");
head = head.link;
}
System.out.println("null");
}
}
输出:
13->33->87->82->35->87->null
关于java - 链表中的节点类,特别是构造函数,并使用它来创建随机整数的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53353793/