gpt4 book ai didi

java - 单链表在尾部插入

转载 作者:行者123 更新时间:2023-12-01 12:41:55 25 4
gpt4 key购买 nike

每次运行此函数时,当我测试函数时,它都会返回一堆: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

最佳答案

您创建了两个不同的链接,而不是仅一个。

你的其他应该是:

 } else {
tail.next = new Node(newItem);
tail = tail.next;
}

实际上,你可以让它变得更简单。在所有情况下,只需使用 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

关于java - 单链表在尾部插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25023892/

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