1
我是Go新手,正在嘗試實現一個非常簡單的鏈接列表。目前,雖然遞歸遍歷列表我試圖擺脫for循環,如果node.next是零/未設置,但if條件永遠不會滿足。我只能假設值不是零,而是某種指向空的節點結構類型的指針,但我無法弄清楚如何評估它。這裏是我的代碼,任何幫助將是非常讚賞:嘗試在Go中測試空的自引用結構值
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)
}