create a linked list in go

To create a linked list in Go, we need to first define a struct that represents a node in the list. The node should have a value field to store the data and a next field to point to the next node in the list.

main.go
type Node struct {
    value interface{}
    next  *Node
}
59 chars
5 lines

We also need to define a struct to represent the linked list itself. It should have a head field that points to the first node in the list.

main.go
type LinkedList struct {
    head *Node
}
42 chars
4 lines

To add a node to the linked list, we can define a method on the LinkedList struct that takes a value as an argument and creates a new node with that value. If the linked list is empty, the new node becomes the head. Otherwise, we traverse the list to find the last node, and set its next field to the new node.

main.go
func (list *LinkedList) AddNode(value interface{}) {
    node := &Node{value, nil}

    if list.head == nil {
        list.head = node
    } else {
        last := list.head
        for last.next != nil {
            last = last.next
        }
        last.next = node
    }
}
277 chars
14 lines

To print the values in the linked list, we can define another method on the LinkedList struct that traverses the list and prints each node's value.

main.go
func (list *LinkedList) Print() {
    node := list.head
    for node != nil {
        fmt.Println(node.value)
        node = node.next
    }
}
143 chars
8 lines

Here's an example usage of the LinkedList:

main.go
func main() {
    list := LinkedList{}
    list.AddNode("apple")
    list.AddNode("banana")
    list.AddNode("cherry")
    list.Print()
}
138 chars
8 lines

Output:

main.go
apple
banana
cherry
20 chars
4 lines

gistlibby LogSnag