find the length of a linked list in go

To find the length of a linked list in Go, we have to traverse the entire list and count the number of nodes. We can do this by starting at the head of the linked list and moving to the next node until we reach the end of the list.

Here's an example implementation:

main.go
type Node struct {
    data int
    next *Node
}

func findLength(head *Node) int {
    current := head
    length := 0

    for current != nil {
        length++
        current = current.next
    }

    return length
}
221 chars
17 lines

In this implementation, we start at the head of the linked list and set a current variable to the head. We also set a length variable to 0.

We then enter a for loop that continues until current is nil (i.e., we have reached the end of the list). For each node in the list, we increment length and move current to the next node.

Once we have finished traversing the list, we return the value of length.

To use this function, we first need to create a linked list. Here's an example of how to create a linked list with three nodes and find its length:

main.go
func main() {
    // Create the linked list: 1 -> 2 -> 3 -> nil
    head := &Node{data: 1}
    head.next = &Node{data: 2}
    head.next.next = &Node{data: 3}

    // Find the length of the linked list
    length := findLength(head)
    fmt.Println("Length:", length)
}
269 chars
11 lines

This will output:

main.go
Length: 3
10 chars
2 lines

gistlibby LogSnag