java - 从链表中删除对象的方法
问题描述
我没有看到我的错误,请纠正我!我需要从 Linkedlist 中删除一个对象。但我收到一个错误 NPEif (current.item.equals(e))
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
属性。我假设最多应该删除一个节点
推荐阅读
- javascript - 创建 ES6 JavaScript 类成员的最有效方法是什么?
- python - 迭代目录中的文件并将具有相同名称的文件放入不同的列表中
- dplyr - 没有适用于 'mutate_' 的方法应用于“c('matrix', 'double', 'numeric') 类的对象
- phpstorm - 如何在 PhpStorm 中的 PHP 文件中突出显示 HTML
- dart - 这两个typedef有什么区别?
- java - 如果文件/连接资源在运行时未关闭,如何查找 Java 资源泄漏。?
- javascript - 如何使用 JXA 替换 Pages (iWork) 中的 placeholderTexts?
- r - 使用列的内容在 R 中创建一个新列
- activemq - ActiveMQ Prometheus Metrics,如 enque deque count 用于监控
- neural-network - 循环尖峰神经网络