gpt4 book ai didi

java - 为什么将新节点添加到链表前面在我的代码中不起作用?

转载 作者:行者123 更新时间:2023-11-30 08:49:57 25 4
gpt4 key购买 nike

为什么我不能像下面这样向我的链表中插入一个新节点?我的 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() 方法所做的就是将当前 root 节点附加为 next 节点insertNew 节点。执行 root = n; 在方法之外没有任何效果,因为它只是一个本地变量。

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

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

关于java - 为什么将新节点添加到链表前面在我的代码中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31226398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com