我是 Go 的新手,正在嘗試實現一個非常簡單的鏈表。目前,在遞歸遍歷列表時,如果 node.next 為 nil/unset,我試圖跳出 for 循環,但 if 條件永遠不會滿足。我只能假設該值不是 nil,而是某種指向空 Node 結構類型的指針,但我不知道如何評估它。這是我的代碼,任何幫助將不勝感激:package mainimport "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)}
1 回答

翻翻過去那場雪
TA貢獻2065條經驗 獲得超14個贊
修正你的錯字:node.next == nilnot node.data == nil。并修復您的遞歸錯誤:刪除for循環。更好的是,為了安全,請檢查node == 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
- 1 回答
- 0 關注
- 141 瀏覽
添加回答
舉報
0/150
提交
取消