1 回答

TA貢獻1824條經驗 獲得超5個贊
問題的根源是調用head.insertAtBegining(30)不會改變 head 的值(它仍然指向node{42, nil})。
你已經開發了這個假設n = nnininsertAtBegining會更新head,但事實并非如此。我認為如果insertAtBegining是標準函數而不是方法更容易理解:
insertAtBegining(head, 30)
...
func insertAtBegining(n *node, d int) *node{
nn := &node{d,n}
n = nn
}
由于 Go 通過值傳遞所有參數(您可以傳遞一個指針,但它作為一個值傳遞)我認為很明顯這不會改變head(如果你想這樣做,你需要定義函數func insertAtBegining(n **node, d int) *node{并傳遞它&head。
您的方法中的問題是相同的。
最簡單的解決方法是重新定義insertAtBegining為(playground):
func (n *node) insertAtBegining(d int) *node{
nn := &node{d,n}
return nn
}
它現在返回新的頭部,所以你可以像這樣使用它head = head.insertAtBegining(30):
另一種方法是將列表管理封裝在一個結構中;這是在list.List中采用的方法。這樣做的好處是用戶不需要了解列表是如何存儲的。
- 1 回答
- 0 關注
- 145 瀏覽
添加回答
舉報