尝试在Go中测试空的自引用结构值
我是新手,正在尝试实现一个非常简单的链表。当前,在递归遍历列表时,我试图在node.next为nil/unset时中断for循环,但if条件从未满足。我只能假设该值不是nil,而是指向空节点结构类型的某种指针,但我不知道如何计算它。这是我的代码,任何帮助都将不胜感激:尝试在Go中测试空的自引用结构值,go,struct,Go,Struct,我是新手,正在尝试实现一个非常简单的链表。当前,在递归遍历列表时,我试图在node.next为nil/unset时中断for循环,但if条件从未满足。我只能假设该值不是nil,而是指向空节点结构类型的某种指针,但我不知道如何计算它。这是我的代码,任何帮助都将不胜感激: package main import "fmt" type Node struct { data string next *Node } func PrintList(node *Node) { for
package main
import "fmt"
type Node struct {
data string
next *Node
}
func PrintList(node *Node) {
for {
fmt.Println(node.data)
if node.data == nil {
break
} else {
PrintList(node.next)
}
}
}
func main() {
node3 := &Node{data: "three"}
node2 := &Node{data: "two", next: node3}
node1 := &Node{data: "one", next: node2}
PrintList(node1)
}
修正您的输入错误:
node.next==nil
notnode.data==nil
。并修复递归错误:删除for
循环。更好的是,为了安全起见,检查节点==nil。比如说,
package main
import "fmt"
type Node struct {
data string
next *Node
}
func PrintList(node *Node) {
if node == nil {
return
}
fmt.Println(node.data)
PrintList(node.next)
}
func main() {
node3 := &Node{data: "three"}
node2 := &Node{data: "two", next: node3}
node1 := &Node{data: "one", next: node2}
PrintList(node1)
}
输出:
one
two
three