[英]Method to delete object from Linked list
我没有看到我的错误,请纠正我! 我需要从 Linkedlist 中删除一个对象。 但是我在if (current.item.equals(e))
遇到了错误 NPE
public void remove(T e) {
if (first == null) {
throw new IndexOutOfBoundsException("List is empty");
}
if (first.item.equals(e)) {
first = first.next;
first.next.prev = null;
}
if (last.item.equals(e)) {
last = last.prev;
last.prev.next = null;
} else {
Node<T> current = first;
for (int a = 0; a < size; a++) {
current = current.next;
if (current.item.equals(e)) {
current.prev.next = current.next;
current.next.prev = current.prev;
}
}
size--;
System.out.println("Removed");
}
}
Linkedlist<String> list = new Linkedlist<>();
list.put("Maria");
list.put("Ales");
list.put("zina");
list.put("bina");
list.put("fina");
list.remove("zina");
一些问题:
你的代码太乐观了。 有几种边界情况您应该检查null
值。
处理第一个或最后一个节点匹配的代码块重新连接错误的节点。
删除第一个或最后一个节点时不调整size
值
当没有找到匹配时, size
仍然递减。
更正的版本与评论:
public void remove(T e) {
if (first == null) {
throw new IndexOutOfBoundsException("List is empty");
}
if (first.item.equals(e)) {
first = first.next;
// first can be null now!
if (first != null) {
// As you already moved the `first` reference, you should not go to next:
first.prev = null;
}
} else if (last.item.equals(e)) { // make this an else if
last = last.prev;
// As you already moved the `last` reference, you should not go to prev:
last.next = null;
} else {
Node<T> current = first.next; // can go to next here already
// avoid current to be null, so make it the loop condition
while (current) {
if (current.item.equals(e)) {
current.prev.next = current.next;
current.next.prev = current.prev;
// No need to continue. Just exit here
break;
}
current = current.next;
}
if (current == null) return; // Not found! We should not decrement the size
}
// Size must be decremented here, since it also applies to head/tail removals!
size--;
System.out.println("Removed");
}
last = last.prev;
我们可以确定last
不是null
。 如果是这样,那么last
的原始值等于first
,那么我们永远不会到达这里。
在if (current.item.equals(e)) {
块中,我们可以确定current.prev
和current.next
都不为空。 如果它们是,那么current
将代表第一个/最后一个节点,我们已经得出结论认为它们不匹配。
我假设所有节点都保证具有item
属性。
我认为最多应该删除一个节点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.