链表中的节点 class 特别是构造函数并使用它来创建随机整数的链表

The node class in linked lists specifically the constructor and using it to create a linked list of random integers

我的节点构造函数如下所示:

 public Node(int ndata, Node nlink)
         {
             this.data=ndata; 
             this.link = nlink; 
         }

这个构造函数有两个参数,节点的数据和下一个节点的link。然而,对于我所看到的构成 linked 列表的所有内容,都会像这样创建一个新节点:

节点nextNode = new Node(data);

但是,如果我出于某种原因没有将第二个参数放入程序中,我就无法 运行 程序。这是我的代码。

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;     

    // ...  
}

我是 linked 列表的新手,所以这让我很困惑,即使这可能是一件我没有理解的非常简单的事情。

您的代码中有几点需要考虑:

  1. 除了 current 之外,您还需要一个 head 变量,最终 return 给调用者(这已被注释掉,所以您在正确的轨道)。

  2. 您第一次调用 current.getLink() 会崩溃,因为 current 开始时是 null

  3. 这个构造函数对于Node是正常的。您可以将 null 作为下一个节点的临时占位符传递给第二个参数,假设您有一个 setter 供您稍后使用。您可能希望重载构造函数以支持 link 作为可选参数,但如果您无权编辑 class.

  4. 则没有必要
  5. ListGenerator 中添加 Scanner 不必要地将其用法限制为仅供用户输入。这个 I/O 逻辑最好放在你的 main 方法中(或者任何调用范围)。进一步沿着这些思路,考虑传递一个节点值数组并将随机数生成也移出该方法,进一步增加 modularity/reusability.

  6. Java 中的方法名称应采用小驼峰格式。

  7. 方法顶部的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

Try it!