【发布时间】:2013-11-28 20:11:21
【问题描述】:
我正在尝试创建一个包含项目的链接列表,它似乎正在添加到列表中,因为我添加了三个并且长度表明它在列表中有 3 个项目。
我的删除功能如何不起作用我正在尝试从列表中删除具有三个项目的列表中的特定项目,但它只是返回 false 并且不会从列表中删除该项目
public void tableInsert (T newItem) throws TableException {
if (head == null)
head = new Node(newItem);
else {
Node tmp = head;
while (tmp.getNext() != null)
tmp = tmp.getNext();
tmp.setNext(new Node(newItem));
}
}
这是删除功能
public boolean tableDelete (KT searchKey) {
if (head.getItem() == searchKey) {
head = head.getNext();
return true;
}
Node current = head.getNext();
Node prev = head;
while (current!= null) {
if (current.getItem() == searchKey){
prev.setNext(current.getNext());
return true;
}
prev = current;
current = current.getNext();
}
return false;
}
【问题讨论】:
-
尝试调试您的代码。
-
第一步是正确缩进你的代码。这里甚至似乎少了几个大括号。
-
@NPE 建议的
equals似乎是最好的选择。我的第二个猜测是忘记在Node构造函数中设置项目。 -
searchKey不是原始数据,请勿使用==进行比较
标签: java