为什么我不能像下面这样向链表插入新节点?仅当我的返回类型是 Node 本身并且返回 root 时,我的 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()
方法所做的就是将当前 root
节点附加为 的
节点。执行 next
节点insertNewroot = n;
在方法之外没有任何效果,因为它只是一个本地变量。
现在,从技术上讲,新节点已成为列表的根,但您看不到它,因为您仍在从旧的根节点(即从第二个节点)迭代列表。列表现在头部有 0
。
您需要引入另一个类,例如 SinglyLinkedList
或其他类,它保存对根节点的引用并为您操作列表。您不应该将此逻辑添加到您的 Node
类本身中。
关于java - 为什么在链表前面添加新节点在我的代码中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31226398/