为了账号安全,请及时绑定邮箱和手机立即绑定

从队列中删除元素时出错

从队列中删除元素时出错

Go
慕森卡 2022-08-09 20:38:40
func (t *bt) topview() {    if t.root == nil {        return    }    qu := list.New()    topview := make(map[int]*tree)    qu.PushBack(top{t.root, 0})    //fmt.Println(sample.Value.(top).hd)    fmt.Println("top view")    for qu != nil {        sample := qu.Front()        qu.Remove(qu.Front())        for key := range topview {            if key != sample.Value.(top).hd {                topview[sample.Value.(top).hd] = sample.Value.(top).node            }        }        if sample.Value.(top).node.left != nil {            qu.PushBack(top{sample.Value.(top).node.left, sample.Value.(top).hd - 1})        }        if sample.Value.(top).node.right != nil {            qu.PushBack(top{sample.Value.(top).node.right, sample.Value.(top).hd + 1})        }    }    for _, value := range topview {        fmt.Println(value)    }}我得到的这个错误panic: runtime error: invalid memory address or nil pointer dereference[signal SIGSEGV: segmentation violation code=0x1 addr=0x10 pc=0x109e1cf]goroutine 1 [running]:container/list.(*List).Remove(...)    /usr/local/go/src/container/list/list.go:140main.(*bt).topview(0xc000072f60)    /Users/pulkitkundra/work/hackerrank/golang-30/tree.go:100 +0x32fmain.main()    /Users/pulkitkundra/work/hackerrank/golang-30/tree.go:126 +0x108exit status 2我试图将删除行放在延迟中,然后它被卡住了。如果我不删除元素,它就会进入无限循环。我正在尝试实现BST的顶视图代码。不寻求以其他方式创建队列。
查看完整描述

2 回答

?
慕仙森

TA贡献1827条经验 获得超8个赞

紧急错误是由线路引起的

qu.Remove(qu.Front())

因为元素传递给了 qu。Remove() 是,发生这种情况是因为 qu.Front() 在列表为空时返回(即删除所有元素后)nilnil

循环条件

for qu != nil {

是错误的,因为它永远不会被满足,因为它永远不会被满足。qunil

循环应该“直到列表不为空”,即:

for qu.Len() > 0 {

这将防止返回,进而将其传递给并导致紧急错误。qu.Front()nilqu.Remove()


查看完整回答
反对 回复 2022-08-09
?
繁星淼淼

TA贡献1775条经验 获得超11个赞

func (t *bt) topview() {

    if t.root == nil {

        return

    }

    qu := list.New()

    topview := make(map[int]*tree)

    qu.PushBack(top{t.root, 0})

    topview[qu.Front().Value.(top).hd] = qu.Front().Value.(top).node

    //fmt.Println(sample.Value.(top).hd)

    fmt.Println("top view")

    for qu.Len() > 0 {

        sample := qu.Front()

        qu.Remove(qu.Front())

        for key := range topview {

            if key != sample.Value.(top).hd {

                topview[sample.Value.(top).hd] = sample.Value.(top).node

            }

        }

        if sample.Value.(top).node.left != nil {

            qu.PushBack(top{sample.Value.(top).node.left, sample.Value.(top).hd - 1})

        }

        if sample.Value.(top).node.right != nil {

            qu.PushBack(top{sample.Value.(top).node.right, sample.Value.(top).hd + 1})

        }

    }

    for _, value := range topview {

        fmt.Println(value.data)

    }


}


查看完整回答
反对 回复 2022-08-09
  • 2 回答
  • 0 关注
  • 145 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号