我只是在我的 Linkedlist
中实现了 add()
方法,但它并没有真正起作用。我认为“current = new Node(node.data);”使对象指向一个新对象而不是更新原始对象,但我不知道如何解决。有什么方法可以正确更新此节点吗?请帮助,谢谢。
class Node{
int data;
Node next;
Node(int data){
this.data = data;
this.next = null;
}
Node(int data, Node next){
this.data = data;
this.next = next;
}
}
class LinkedList{
protected Node head;
protected int size;
LinkedList(){};
void add(int data)
{
Node node = new Node(data);
if (head == null) {
head = node;
}else {
Node current = head;
while(current != null) {
current = current.next;
}
current = new Node(node.data);
}
size++;
}
public int getSize() {
return size;
}
public String toString()
{
Node current = head;
String result = "";
while(current != null) {
result += current.data +"->";
current = current.next;
}
return result;
}
}
最佳答案
你快到了。你的问题在这里
while(current != null) {
... }
current = new Node(node.data);
这会创建一个新节点,它应该位于列表的最末端。但是您只将新实例分配给 local 变量......然后丢失,因为该方法结束了。
相反,您必须更改循环,直到找到不为 null 的 last 条目,以便 current.next == null
。然后简单地去:
current.next = new Node(node.data);
关于java - 为什么我的 LinkedList 中的 add() 方法不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52713013/