How do I implement a linked list in Go?

In Go, a linked list can be implemented using structs to represent each node. Each node contains a value and a pointer to the next node. Below is an example of a singly linked list implementation in Go.

package main import "fmt" // Node defines a node of the linked list type Node struct { Value int Next *Node } // LinkedList defines the linked list structure type LinkedList struct { Head *Node } // Add adds a new node to the end of the linked list func (l *LinkedList) Add(value int) { newNode := &Node{Value: value} if l.Head == nil { l.Head = newNode return } current := l.Head for current.Next != nil { current = current.Next } current.Next = newNode } // Print prints the linked list func (l *LinkedList) Print() { current := l.Head for current != nil { fmt.Print(current.Value, " ") current = current.Next } } func main() { list := &LinkedList{} list.Add(1) list.Add(2) list.Add(3) list.Print() // Output: 1 2 3 }

linked list Go Go programming data structures singly linked list