从队列中删除元素时出错

getting error while removing the element from queue

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:140
main.(*bt).topview(0xc000072f60)
    /Users/pulkitkundra/work/hackerrank/golang-30/tree.go:100 +0x32f
main.main()
    /Users/pulkitkundra/work/hackerrank/golang-30/tree.go:126 +0x108
exit status 2

我试图将删除行延迟,但它卡住了。 如果我不删除它进入无限循环的元素。 我正在尝试实现 BST 的顶视图代码。 不想以另一种方式创建队列。

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)
    }

}

紧急错误是由行

引起的
qu.Remove(qu.Front())

因为元素传递给 qu.Remove() is nil and this happens because qu.Front() returns nil 当列表为空时(即一旦所有元素都被删除)

循环条件

for qu != nil {

是错误的,因为它永远不会满足,因为 qu 永远不会 nil

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

for qu.Len() > 0 {

这将阻止 qu.Front() 返回 nil 并反过来将其传递给 qu.Remove() 并导致恐慌错误。