2016-03-05 20 views
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) 
} 

回答

3

解決您的錯字:node.next == nil沒有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