go - 从队列中删除元素时出错
问题描述
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 的顶视图代码。不寻找以另一种方式创建队列。
解决方案
恐慌错误是由线路引起的
qu.Remove(qu.Front())
因为传递给的元素qu.Remove()
是nil
并且发生这种情况是因为当列表为空时qu.Front()
返回nil
(即,一旦所有元素都被删除)
循环条件
for qu != nil {
是错的,因为它永远不会相遇,因为qu
永远不会nil
。
循环应该去“直到列表不为空”,即:
for qu.Len() > 0 {
这将防止qu.Front()
返回nil
并反过来将其传递给qu.Remove()
并导致恐慌错误。
推荐阅读
- html - 如何在 3 列网格视图中添加轮播
- java - 如何将 4096 分辨率的图像保存到 android 的设备库中?
- python - 自定义函数的 Python 到 R 转换
- javascript - 如何在 7 位上将字符串转换为二进制?(JavaScript)
- python - 使用 .shift() 选项将当前月利率与基本利率(旧利率)进行比较
- java - 有没有办法在 systemPath 中使用变量来实现系统范围的依赖?
- r - 功能齐全的文件和位置地址未呈现 rstudio rmarkdown::render()
- angular - mat-sidenav push 属性导致构建错误
- javascript - 在 React js 中选择特定下拉值时禁用按钮
- java - Hibernate 抛出 java.sql.SQLException:@Enumerated(EnumType.STRING) 的整数值异常不正确