java - 如何使用具有两个整数参数并返回对节点列表第一个元素的引用的方法构建链表?

标签 java linked-list nodes

所以我在尝试从具有两个整数参数 n 和 m 的方法构建链表时遇到了问题。参数n是链表的节点长度,m是节点列表中包含0到m-1的随机整数的参数。我需要从无法更改的预定义节点类构建此链表,并返回对链表中第一个元素的引用。我不知道如何在while循环中遍历链表。

节点类

public class iNode{
public int item;
public iNode next;

public iNode(int i, iNode n){ 
    item = i; 
    next = n; 
}
public iNode(int i){ 
    item = i; 
    next = null; 
}

建立链表方法

    public static iNode list(int n, int m){

    iNode first; 
    iNode newNode;
    iNode last;


    first = null;
    while ( )
    {
        newNode = new iNode(m, first.next);
        if (m > 0){
            newNode.item = m-1;
        }
        newNode.next = null; 

        if (first == null)
        {
            first = newNode;
            last = newNode;
        }
        else
        {
            last.next = newNode;
            last = newNode;
        }

    }
    return first;
}

最佳答案

你把它复杂化了。只需从列表的末尾开始并添加带有指向前一个节点的链接的节点。最后只返回最后创建的节点。此外,您没有添加 0..m-1 范围内的随机整数。在这里:

    public static void main(String[] args) {
        iNode res = list(5, 10);

        while(res != null){
            System.out.println(res.item);
            res = res.next;
        }
    }

    public static iNode list(int n, int m) {

        iNode previous;
        iNode current;

        int i = 0;
        previous = null;
        while (i < n) {
            current = new iNode(ThreadLocalRandom.current().nextInt(0, m), previous);
            previous = current;

            i++;
        }
        return previous;
    }

输出:

2
5
7
8
9

附言请遵循 java 代码约定。类名应以大写字母开头 - iNode

关于java - 如何使用具有两个整数参数并返回对节点列表第一个元素的引用的方法构建链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46245689/

相关文章:

c++ - 使用循环将随机数添加到链表中

c - 如何从链表中删除第一个节点? (C)

java - nullpointerException 错误删除节点

java - 使用 JGit 获取文件、修改内容并提交

java - Spring mvc-从 PostMapping URL 返回 JSON(Froala 编辑器)

data-structures - 使用 LinkedList 或 ArrayList 进行迭代

java - 在方法内创建节点

java - 为什么我不能从数组创建单链表?

java - 文件写入后无法删除

java - 我的加密程序需要帮助