有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

此构造函数接受两个参数:节点的数据和到下一个节点的链接。然而,对于我所看到的制作链表的一切,一个新的节点是这样创建的:

Node 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;     

    // ...  
}

我不熟悉链表,所以这对我来说很困惑,即使这可能是一件很简单的事情,我也不明白


共 (1) 个答案

  1. # 1 楼答案

    <> P>代码中有几个要点需要考虑:

    1. 除了current之外,您还需要一个head变量才能最终返回到调用方(这已被注释掉,所以您的思路是正确的)

    2. 您对current.getLink()的第一次调用将崩溃,因为currentnull开头

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

    4. ListGenerator中添加Scanner不必要地将其使用限制为仅限于用户输入。这个I/O逻辑最好放在main方法中(或调用范围的任何地方)。进一步沿着这些线,考虑传递一个节点值数组并从方法中移出随机数生成,进一步增加模块化/可重用性。p>

    5. Java中的方法名称应该小写

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