1

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)
}

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.