我有代碼可以從 golang 列表中的最后一個元素中找到第 k 個。我寫了一個遞歸函數(shù)。當(dāng)它到達列表的末尾時,它會將計數(shù)返回為 1,并在進一步返回時遞增。當(dāng) count == k 時返回節(jié)點值。但我收到“零指針取消引用”錯誤。有人可以幫助我嗎?package main import ( "container/list" "fmt")var sMap map[int]boolfunc main() { l := list.New() for i := 1; i < 100; i++ { l.PushBack(i) } kFromLastElemRec := findKFromLastRecr(l.Front(), 3, WrapObj{0}) fmt.Println(kFromLastElemRec.Value.(int)) }//Object to store the count type WrapObj struct { count int}//ERROR//recursive function to find the kth from last elementfunc findKFromLastRecr(head *list.Element, k int, wrapper WrapObj) *list.Element { if head == nil { return nil } resNode := findKFromLastRecr(head.Next(), k, wrapper) wrapper.count = (wrapper.count) + 1 if wrapper.count == k { return head } return resNode}
使用 golang 的列表中最后一個元素的第 K 個
慕桂英3389331
2021-09-10 21:24:28