檢查我的數(shù)據(jù)結(jié)構(gòu),以滿足一些新的工作面試要求。所以我有一個鏈表的刪除方法。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;}我想到目前為止我已經(jīng)明白了。但我對這條線感到好奇。// just bypass itprevious.next = current.next;為什么我們不使用 覆蓋head(在本例中表示為first)previous?或者會是錯誤的邏輯嗎?喜歡// just bypass itprevious.next = current.next;first=previous;我的意思是previous和current只是迭代列表的指針。而刪除后的真實(shí)數(shù)據(jù)位于右側(cè)first?抱歉,如果這樣想會很奇怪。有時我奇怪的直覺只是在研究算法時出現(xiàn),主要是因?yàn)槲矣悬c(diǎn)弱
1 回答

暮色呼如
TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超9個贊
這樣做會導(dǎo)致鏈表丟失前一個節(jié)點(diǎn)之前的所有節(jié)點(diǎn)。如果您有一個包含以下值的鏈接列表:
[1, 2, 3, 4, 5, 6, 7, 8]
當(dāng)你打電話時delete(7)
,你的頭會指向6
,然后你就會得到一個 的鏈接列表[6, 8]
。
添加回答
舉報(bào)
0/150
提交
取消