Golang容器/列表创建邻接表



我试图用golang建立一个邻接表。

package main
import (
"container/list"
"fmt"
)
type SocialGraph struct {
// define the size
V int
// define the type of array of int list, row is the list order, column is the list of neighbors
// whether to create array from make or just define?
Arr map[int]*list.List
}
func AddEdge(g SocialGraph, i, j int, undir bool) {
/*
param g: instance of SocialGraph
param i: edge start
param j: edge end
param undir: whether directed
*/
g.Arr[i].PushBack(j)
if undir {
g.Arr[j].PushBack(i)
}
fmt.Println(g)
}
func PrintEdgeList(g SocialGraph) {
for i := 0; i <= g.V; i++ {
fmt.Printf("the neighbor of %d includes %v n", i, g.Arr[i])
}
}
func main() {
graph := SocialGraph{V: 6, Arr: make(map[int]*list.List, 7)}
fmt.Println(graph)
AddEdge(graph, 1, 3, true)
AddEdge(graph, 2, 3, true)
AddEdge(graph, 2, 4, true)
AddEdge(graph, 1, 5, true)
AddEdge(graph, 1, 6, true)
PrintEdgeList(graph)
}

我用的是list。列表来定义邻居列表,但是我总是得到错误:

container/list.(*List).lazyInit(...)
E:/Go/src/container/list/list.go:86
container/list.(*List).PushBack(...)
E:/Go/src/container/list/list.go:151
main.AddEdge({0xc00002e000?, 0xc00007feb0?}, 0x9b5cca?, 0xc000062000?, 0x1)

我不确定是否应该用map[int][]list定义map中的值。列表或映射[int]*列表。

列表

这个SocialGraph的Arr没有初始化,我认为你应该初始化Arr,就像这样,或者其他初始化方法

func AddEdge(g SocialGraph, i, j int, undir bool) {
/*
param g: instance of SocialGraph
param i: edge start
param j: edge end
param undir: whether directed
*/
if g.Arr[i] == nil {
g.Arr[i] = list.New()
}
g.Arr[i].PushBack(j)
if undir {
if g.Arr[j] == nil {
g.Arr[j] = list.New()
}
g.Arr[j].PushBack(i)
}
fmt.Println(g)
}