[英]Single Linked List Insert at the tail
Every time I run this, it returns a bunch of: null, null, null for the items when I test the function out. 每次运行此函数时,当我测试功能时,它将返回一堆:null,null,null的项目。
//enqueue()
//adds newItem to the back of this Queue
public void insertItemLast(Object newItem){//make sure that it is not empty so we can do the cool stuff in here
if(newItem == null)
return;//user inputs nothing
else {
Node P = new Node(newItem);
P.next = null;
if(head == null){
head = P;
tail = P;
//tail.next = null;
}else{
tail.next = new Node(newItem);
tail = new Node(newItem);
//tail.next = null;
}
}
numItems++;
}//end enqueque
You create two different links instead of just one. 您创建两个不同的链接,而不仅仅是一个。
Your else should be : 您的其他应该是:
} else {
tail.next = new Node(newItem);
tail = tail.next;
}
Actually, you can make it even simpler. 实际上,您可以使其更简单。 Just use P for the new link of the list in all cases :
在所有情况下,只需将P用作列表的新链接:
public void insertItemLast(Object newItem){
if(newItem == null)
return;//user inputs nothing
else {
Node P = new Node(newItem);
P.next = null;
if(head == null) {
head = P;
tail = P;
} else {
tail.next = P;
tail = P;
}
}
numItems++;
}//end enqueque
You correctly assigned a new Node
to tail.next
, but you didn't update tail
; 您正确地为
tail.next
分配了一个新的Node
,但是没有更新tail
。 you instead assigned another new Node
to tail
, effectively breaking the tail off of the list. 您改为将另一个新
Node
分配给tail
,从而有效地将尾部从列表中断开。
To advance the old tail
to the new tail
-- the newly inserted Node
-- replace 将旧
tail
移到新tail
-新插入的Node
替换
tail = new Node(newItem);
with 同
tail = tail.next;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.