亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

嘗試在 Go 中測試空的自引用結構值

嘗試在 Go 中測試空的自引用結構值

Go
翻閱古今 2021-12-20 15:16:24
我是 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


查看完整回答
反對 回復 2021-12-20
  • 1 回答
  • 0 關注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號