【发布时间】:2020-12-20 17:54:28
【问题描述】:
确定单链表是否包含循环是一个常见问题,您将如何创建带有循环的链表?我正在尝试在 golang 中解决它。
package main
import "fmt"
type node struct {
data int
nextnodepointer *node
}
type linkedList struct {
headnode *node
length int
}
func (l *linkedList) prepend(n *node) {
temp := l.headnode
if l.headnode == nil {
fmt.Println("headnode is nil")
fmt.Println(n)
temp = n.nextnodepointer
}
l.headnode = n
n.nextnodepointer = temp
l.length++
}
func (l linkedList) printData() {
toPrint := l.headnode
for l.length != 0 {
fmt.Printf("%v\t", toPrint)
toPrint = toPrint.nextnodepointer
l.length--
}
fmt.Println()
}
func main() {
var n1, n2, n3, n4, n5, n6 *node
myList := linkedList{}
n6 = &node{data: 60, nextnodepointer: n3}
n5 = &node{data: 50, nextnodepointer: n6}
n4 = &node{data: 40, nextnodepointer: n5}
n3 = &node{data: 30, nextnodepointer: n4}
n2 = &node{data: 20, nextnodepointer: n3}
n1 = &node{data: 10, nextnodepointer: n2}
myList.prepend(n6)
myList.prepend(n5)
myList.prepend(n4)
myList.prepend(n3)
myList.prepend(n2)
myList.prepend(n1)
myList.printData()
}
所以我试图像这样解决它,节点 n6 的下一个节点是 n3 但由于它当时没有定义 n3 是 nil 这导致 printData 函数打印链表的内容像这样&{10 0xc000010240} &{20 0xc000010230} &{30 0xc000010220} &{40 0xc000010210} &{50 0xc000010200} &{60 <nil>}。节点n6 的下一个节点指针为nil,因为n3 是nil。如何在 golang 中创建带有循环的链表?
【问题讨论】:
标签: algorithm go linked-list circular-list