我有代码从golang中的列表中的最后一个元素中找到kth。我写了一个递归函数。当它到达列表的末尾时,它将计数返回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
}
答案 0 :(得分:1)
您需要将指向WrapObj
的指针传递给findKFromLastRecr()
函数。
与C系列中的语言类似,Go中的所有内容都按值传递。也就是说,函数总是获取正在传递的东西的副本,就好像有一个赋值语句将值赋给参数。
例如,将WrapObj
值传递给函数会复制WrapObj
,但不会复制它指向的WrapObj
。
因此,如果没有指向WrapObj
的指针,则每个findKFromLastRecr()
函数都会获得WrapObj
的副本,并且外部findKFromLastRecr()
函数无法共享增加。
从golang-book中查看pointers部分可能很有用。
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
}
输出
97