該函式遞回地計算單鏈表的長度。
tail是一個實體變數,指向串列中的下一個物件。
public int length() {
if (tail == null) {
return 1;
}
return 1 tail.length();
}
但是,它不使用任何引數,如圖所示。我正在努力理解這段代碼背后的邏輯,我能在理解這里實際發生的事情方面得到一些幫助嗎?
我的第一個困惑點是當函式到達串列中的最后一個物件時,物件尾部將為空,那么為什么函式最終不回傳 1?其次,1 tail.length()實際上做了什么。
我最了解的是,由于函式的回傳型別為 int 1,因此tail.length()可以添加它。length
uj5u.com熱心網友回復:
假設您有一個類似的串列[a, b, c, d]并且您正在呼叫length()它。this最初將是第一個元素a,tail并將成為下一個元素b。所以代碼的流程應該是這樣的:
this.length() // Element 'a'
Is tail == null? // No, tail is 'b'
return 1 <result of length() of 'b'>
|
| this.length() // Element 'b'
| Is tail == null? // No, tail is 'c'
| return 1 <result of length() of 'c'>
| |
| | this.length() // Element 'c'
| | Is tail == null? // No, tail is 'd'
| | return 1 <result of length() of 'd'>
| | |
| | | this.length() // Element 'd'
| | | Is tail == null? // Yes, there's no element after 'd' so return 1
| | | return 1 // return 1 from length() of 'd'
| | |
| | return 1 1 // return 2 from length() of 'c'
| |
| return 1 2 // return 3 from length() of 'b'
|
return 1 3 // return 4 from length() of 'a'
所以最后,length()會給你正確的結果4
uj5u.com熱心網友回復:
成員函式總是有 1 個引數......您呼叫該函式的物件(this在 function.
你打電話時
return 1 tail.length();
該函式length將有一個this指的是tailhere。在tail那個函式中是tail.tail
uj5u.com熱心網友回復:
當函式到達串列中的最后一個物件時,該物件的尾部將為空,那么為什么函式最終不回傳 1?
它確實 - 當在串列中的最后一個物件上呼叫時。
1 tail.length() 實際上做了什么。
它呼叫物件length。tail當你說它“沒有引數”時,你并不完全正確——引數是它被呼叫的物件。因此,如果您呼叫node.length()wherenode.tail == tail1和tail1.tail == null,那么node.length()is 1 tail1.length()is1 1是 2,總長度為 2——這是我們所期望的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/523830.html
標籤:爪哇算法数据结构dsa
