I am new to Go and am trying to implement a very simple linked list. Currently while recursively traversing the list I am attempting to break out of the for loop if node.next is nil/unset, but the if conditional is never satisfied. I can only assume that the value is not nil, but some sort of pointer to an empty Node struct type, but I can't figure out how to evaluate this. Here is my code, any help would be much appreciated:
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)
}
Fix your typo:node.next == nil
not node.data == nil
. And fix your recursion error: delete the for
loop. Even better, for safety, check for node == nil
. For example,
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)
}
Output:
one
two
three