所以我試圖通過索引檢索 minheap 樹中的節點。呼叫它的方式是我將啟動一個空的 MinHeapNode 結構并通過它的值傳遞,&node以便在遞回函式呼叫之間,如果找到匹配項,它將回傳。然而,似乎即使給出了找到的結果,新分配的空節點也會被另一個具有該節點空版本的遞回呼叫覆寫。我仍然習慣于指標和地址的想法,所以我相信傳遞值地址可以解決這個問題,因為它會在呼叫之間的相同地址呼叫相同的值。但顯然這是不正確的。
type MinHeapNode struct {
Parent *MinHeapNode
Left *MinHeapNode
Right *MinHeapNode
Value int
Index int
}
func (MHN *MinHeapNode) Insert(value int) {
if !MHN.hasLeftChild() {
MHN.Left = &MinHeapNode{Parent: MHN, Value: value}
return
}
if !MHN.hasRightChild() {
MHN.Right = &MinHeapNode{Parent: MHN, Value: value}
return
}
if MHN.hasLeftChild(){
MHN.Left.Insert(value)
return
}
if MHN.hasRightChild(){
MHN.Right.Insert(value)
return
}
}
func (MHN *MinHeapNode) setIndex(count *int){
index := *count
*count = *count 1
MHN.Index = index
if MHN.hasLeftChild(){
MHN.Left.setIndex(count)
}
if MHN.hasRightChild(){
MHN.Right.setIndex(count)
}
}
func (MHN *MinHeapNode) getIndex(index int, node *MinHeapNode){
if MHN == nil{
return
}
if MHN.Index == index{
node = MHN
return
}
MHN.Left.getIndex(index, node)
MHN.Right.getIndex(index,node)
}
}
type MinHeapTree struct {
Root MinHeapNode
Size int
}
func (MHT *MinHeapTree) getIndex(index int)(*MinHeapNode, error){
if MHT.Size < index 1 {
err := fmt.Errorf("index exceeds tree size")
return nil, err
}
var node MinHeapNode
MHT.Root.getIndex(index, &node)
return &node, nil
}
uj5u.com熱心網友回復:
您面臨的問題似乎與中的陳述句node = MHN有關getIndex(但由于您的代碼不完整,我無法確認這是否是唯一的問題)。
node = MHN將更新node(一個引數,因此按值傳遞,其范圍是函式體)的值。MinHeapNode這對函式node開頭指向的值沒有影響。糾正這種用法*node = *MHN。
這可以用一個簡單的程式(操場)來演示
type MinHeapNode struct {
Test string
}
func getIndexBad(node *MinHeapNode) {
newNode := MinHeapNode{Test: "Blah"}
node = &newNode
}
func getIndexGood(node *MinHeapNode) {
newNode := MinHeapNode{Test: "Blah"}
*node = newNode
}
func main() {
n := MinHeapNode{}
fmt.Println(n)
getIndexBad(&n)
fmt.Println(n)
getIndexGood(&n)
fmt.Println(n)
}
輸出表明“壞”函式不會更新傳入的node:
{}
{}
{Blah}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/449672.html
