有 Java 编程相关的问题?

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

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

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

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

    }

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

比如说,

LinkedList当前为10->;20->;三十

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

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

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

为什么?


共 (2) 个答案

  1. # 1 楼答案

    head是一个局部变量,因此在insert(Node head, int data)中为它赋值不会影响传递给方法的Node

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

    使用传递的Node参数修改列表的唯一方法是,该方法是否会更改该NodenextLink

  2. # 2 楼答案

    在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);