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

标签 java linked-list nodes computer-science

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

 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;     

    // ...  
}

我是链表新手,所以这对我来说非常困惑,即使这可能是我没有得到的非常简单的事情。

最佳答案

在您的代码中需要考虑以下几点:

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

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

  3. 此构造函数对于 Node 是正常的。 。您可以通过null进入第二个参数作为下一个节点的临时占位符,假设您有一个供以后使用的 setter。您可能希望重载构造函数以支持 link作为可选参数,但如果您无权编辑该类,则没有必要。

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

  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!

关于java - 链表中的节点类,特别是构造函数,并使用它来创建随机整数的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53353793/

相关文章:

java - 使 Struts2 redirectAction 使用相对路径而不是绝对路径

java - 生成圆半径坐标到KML中的坐标

java - 以实数为根生成随机二次方程

c - 如何在不转换为字符串的情况下一次传递多个整数

algorithm - 扩展节点是什么意思?

java - Java中复合赋值运算符的运算顺序

c - 在 C 中通过双指针访问结构元素

c - 带有 bug 的链表的哈希表

database - 如何停止 Neo4j 中节点的移动?

latex - 将两个相邻节点的边界放置在彼此的顶部