我有代码可以从 golang 列表中的最后一个元素中找到第 k 个。我写了一个递归函数。当它到达列表的末尾时,它会将计数返回为 1,并在进一步返回时递增。当 count == k 时返回节点值。但我收到“零指针取消引用”错误。有人可以帮助我吗?
package main
import (
"container/list"
"fmt"
)
var sMap map[int]bool
func 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 element
func 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
}
相关分类