Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 此代码有什么问题(简单LinkedList)_Java_Linked List - Fatal编程技术网

Java 此代码有什么问题(简单LinkedList)

Java 此代码有什么问题(简单LinkedList),java,linked-list,Java,Linked List,所以,我研究了链表,并创建了这个插入方法 private void insert(Node head, int data) { Node node = new Node(data); Node first = head; if(first == null) { head = node; } else { node.nextLi

所以,我研究了链表,并创建了这个插入方法

private void insert(Node head, int data)
    {
        Node node = new Node(data);

        Node first = head;

        if(first == null)
        {
            head = node;
        }
        else
        {
            node.nextLink = first;
            head = node;
            //System.out.println(node.data);
        }
    }
这种导线测量方法

public void traversingLinkedList(Node head)
    {
        Node current = head;

        while(current != null)
        {
            int data = current.data;
            System.out.println(data);
            current = current.nextLink;
        }

    }
但是当我插入节点时,它没有显示节点。 当我在insert方法中取消对打印行的注释时,会显示节点数据

比如说,

LinkedList当前为10->20->30

使用插件后(头,4) 我仍然得到10->20->30

尽管在方法中,当我取消选中打印方法时插入 它将第一个节点数据显示为4

但当穿越时,它并没有显示出来


为什么?

head
是一个局部变量,因此在
insert(节点头,int数据)
中为其赋值不会影响传递给方法的
节点

如果您的
insert
方法是某个
LinkedList
类的一部分,则该类应包含对列表标题的引用,并且
insert
应分配给该引用。在这种情况下,您不需要将
节点头
作为参数传递给
插入


使用传递的
节点
参数修改列表的唯一方法是,如果该方法将更改该
节点
nextLink
,则在Java中调用方法时,将复制而不是引用变量。这意味着在您的情况下,
insert
方法内的变量
head
仅为局部变量,其修改在方法外不可见

因此,由于您在前面插入元素,因此插入后的新头是您创建的节点(而不是上一个),您需要返回它以更新下一个调用。此外,您可以简化insert方法的代码,因为您将始终更新head值,唯一的条件部分是列表中是否有更多元素

private Node insert(Node head, int data)
{
    Node node = new Node(data);

    if (head != null) {
        node.nextLink = head;
    }

    head = node;

    return head;
}
在这种情况下,您的主要方法应该如下所示:

// LinkedList 10->20->30
head = new Node(30);
head = insert(head, 20);
head = insert(head, 10);

// Add the new 4 head: 4->10->20->30
head = insert(head, 4);
// Traversing
traversingLinkedList(head);

似乎您正在前面插入元素。您的insert方法不应该返回新的head元素吗?(它是,节点?)它应该。我发现的一个错误是,在主方法中,我设置节点head=ob1,所以每次只取head=ob1(即10)。如何解决这个问题?你的insert方法应该返回新head的值,它应该更新调用函数的head值。好的!知道了。我发现了我的错误。在我的main方法中,我分配了Node head=ob1(ie 10),所以每次调用方法时都只将head作为那个值。现在,我将insert方法的返回类型更改为Node,并指定head=insert(head,4)来更新它本身!谢谢。@JoeBrown我不确定在
main
方法中将列表的开头作为局部变量是不是一个好主意。通常,列表的开头是LinkedList类的实例变量。只有LinkedList类的方法才能更改列表的标题。