Laurent Knauss Software Engineer
Linked List illustration

A Linked List in Golang with Generics

A linked list is a sequence of nodes where each node points to the next one.
A singly linked list stores a reference only to the next node, while a doubly linked list stores references to both previous and next nodes.

Singly Linked List Example

package main

import (
  "fmt"
)

type Node[T any] struct {
  data T
  next *Node[T]
}

type LinkedList[T any] struct {
  head   *Node[T]
  length int
}

func (ll *LinkedList[T]) Append(data T) {
  newNode := &Node[T]{data: data}
  if ll.head == nil {
    ll.head = newNode
  } else {
    current := ll.head
    for current.next != nil {
      current = current.next
    }
    current.next = newNode
  }
  ll.length++
}

func (ll *LinkedList[T]) Prepend(data T) {
  newNode := &Node[T]{data: data, next: ll.head}
  ll.head = newNode
  ll.length++
}

func (ll *LinkedList[T]) Print() {
  current := ll.head
  for current != nil {
    fmt.Printf("%v ", current.data)
    current = current.next
  }
  fmt.Println()
}

func main() {
  list := LinkedList[int]{}
  list.Prepend(2)
  list.Prepend(1)
  list.Append(3)
  fmt.Printf("List contents (%d nodes): ", list.length)
  list.Print()
}

Running this program prints:

List contents (3 nodes): 1 2 3
    How to Code a Linked List in Golang | Laurent