Java 为什么在我的代码中向链表前面添加新节点不起作用?

Java 为什么在我的代码中向链表前面添加新节点不起作用?,java,linked-list,singly-linked-list,Java,Linked List,Singly Linked List,为什么我不能按如下方式将新节点插入到链接列表中?只有当返回类型为节点本身且返回根时,insertNodeToHead才起作用。但是我希望能够在不返回任何内容的情况下更改链表本身。目前,它应该打印0,1,2,3,4,但只打印1,2,3,4 这是我的密码: // Create a singly linked list class public class Node { int data; Node next = null; public Node (int age) {

为什么我不能按如下方式将新节点插入到链接列表中?只有当返回类型为节点本身且返回根时,insertNodeToHead才起作用。但是我希望能够在不返回任何内容的情况下更改链表本身。目前,它应该打印0,1,2,3,4,但只打印1,2,3,4

这是我的密码:

// Create a singly linked list class
public class Node {
    int data;
    Node next = null;

    public Node (int age) {
        data = age;
    }

    // insert a node to the head of a linked list
    public void insertNodeToHead (Node n) {
        Node root = this;
        n.next = root;
        root = n;
        return;

    }


    public static void main(String[] args) {
        Node root = new Node(1);
        root.next = new Node(2);
        root.next.next = new Node(3);
        root.next.next.next = new Node(4);

        // insert new node
        Node insertNew = new Node(0);
        root.insertNodeToHead(insertNew);

        Node current = root;
        while (current != null) {
            System.out.println(current.data); 
            current = current.next;
        }
    }
}

那么,您的
insertNodeToHead()
方法所做的就是将当前
根节点作为
insertNew
节点的
下一个
节点。做
root=n
在方法之外没有效果,因为它只是一个局部变量

现在,从技术上讲,新节点已成为列表的根节点,但您无法看到它,因为您仍在从旧的
根节点
迭代列表,即从列表的第二个节点开始,该节点现在的头部为
0


您需要引入另一个类,例如
SinglyLinkedList
或其他类,它保存对根节点的引用并为您操作列表。您不应该将此逻辑添加到
节点
类本身

您的
表示此节点:
节点根=新节点(1)
您想要的是在
insertNodeToHead
方法中设置
this=n
,但是如果使用
void
方法,则无法使
this
指向另一个节点。拉维·塔普里亚尔的回答解释了这一点

一种解决方案是Ravi Thapliyal的建议,它使用另一个类来保存对根节点的引用。如果不想引入新类,建议使用返回
Node
type的方法来实现您的要求:

public class Node {
    int data;
    Node next = null;

    public Node (int age) {
        data = age;
    }

    // insert a node to the head of a linked list and return the head
    public Node insertNodeToHead(Node n) {
        n.next = this;
        return n;
    }


    public static void main(String[] args) {
        Node root = new Node(1);
        root.next = new Node(2);
        root.next.next = new Node(3);
        root.next.next.next = new Node(4);

        // insert new node
        Node insertNew = new Node(0);
        Node current = root.insertNodeToHead(insertNew);

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

你能解释一下你的
insertNodeToHead
方法具体是做什么的吗?假设我的链表是1->2->3->4。现在,如果我想将新节点(0)添加到此列表中,我的新列表应该是0->1->2->3->4我不是问它应该做什么,而是问它做什么。带我们走过去。哦,对不起。因此,它首先为节点的当前实例创建一个变量“root”。然后要添加的新节点“n”指向根,然后“n”成为根本身。但是,实例没有改变。我不能做“this=root”,因为java给了我一个错误,告诉我赋值的左侧必须是一个变量本身。