【发布时间】:2023-04-11 07:08:01
【问题描述】:
为什么我不能在我的链表中插入一个新节点,如下所示?我的 insertNodeToHead 仅在我的返回类型是 Node 本身并且我返回 root 时才有效。但我希望能够在不返回任何内容的情况下更改链接列表本身。目前,它应该打印 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方法的作用吗,具体来说? -
假设我的链表是 1->2->3->4。现在如果我想将新节点(0)添加到这个列表中,我的新列表应该是 0->1->2->3->4
-
我不是在问它应该做什么,我是在问它做什么。引导我们完成它。
-
哦,对不起。因此,首先它为节点的当前实例创建一个变量“root”。然后要添加的新节点“n”指向根,然后“n”成为根本身。但是,实例不会改变。我不能做“this = root”,因为 java 给我一个错误,说赋值的左侧必须是一个变量本身”。我想改变实例本身。
标签: java linked-list singly-linked-list