![](/img/trans.png)
[英]If we check head==null why don't we check tail==null in Java linkedlist?
[英]LinkedList delete : why don't we override the head with previous?
查看我的數據結構,了解一些新的工作面試要求。 所以我有一個鏈接列表的刪除方法。
public Link delete(int key) {
Link current = first;
Link previous = first;
while(current.iData != key) {
if(current.next == null)
return null;
else {
previous = current;
current = current.next;
}
}
if(current == first)
first = first.next;
else
// just bypass it
previous.next = current.next;
return current;
}
我想我到目前為止都明白了。 但我對這條線很好奇。
// just bypass it
previous.next = current.next;
為什么我們不用previous
一個覆蓋head
(在這個例子中表示為first
)? 或者會是錯誤的邏輯嗎? 喜歡
// just bypass it
previous.next = current.next;
first=previous;
我的意思是previous
和current
只是迭代列表的指針。 而刪除后的真實數據位於first
對嗎? 抱歉,如果這樣想會很奇怪。 有時我奇怪的直覺只是在學習算法時出現,主要是因為我有點弱
這樣做會導致您的鏈表丟失前一個節點之前的所有節點。 如果您有一個包含以下值的鏈表:
[1, 2, 3, 4, 5, 6, 7, 8]
並且您調用了delete(7)
,您的頭部將指向6
,並且您將擁有一個[6, 8]
的鏈表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.