我正在尝试将一个节点添加到列表的末尾,这就是我想到的。我只是想知道我是否设置 tail=head 是否与 tail=add 相同?或者如果我有 tail=head.next 如果它与 tail=add 相同? 提前致谢
public BasicLinkedList<T> addToEnd(T data) {
Node add= new Node(data);
Node curr=head;
if(size==0){
head= add;
tail=head; //is it okay to make this= head? Or should it be =add?
}else if(size==1){
head.next=add;
tail=head.next; //is it okay to make this= head.next? Or should it be =add?
}else{
while(head.next!= null){
curr=head.next;
}curr.next = add;
tail = add;
}
size++;
return this;
}
最佳答案
关于答案
//is it okay to make this= head? Or should it be =add?
是的,两者都可以,head
和 add
是对同一对象的引用。
和
//is it okay to make this= head.next? Or should it be =add?
同样,这里也可以,因为 head.next
和 add
是对同一对象的引用。
关于Java-Node 清晰度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42382303/