[英]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.