0
0
GoHow-ToBeginner · 3 min read

How to Implement Linked List in Go: Simple Guide with Example

To implement a linked list in Go, define a Node struct with a value and a pointer to the next node. Then create methods to add, traverse, or remove nodes by updating these pointers.
📐

Syntax

A linked list in Go uses a struct to represent each node. Each node holds data and a pointer to the next node. The list is managed by keeping a reference to the first node, called the head.

  • Node struct: Holds the value and pointer to the next node.
  • Head pointer: Points to the first node in the list.
  • Next pointer: Links nodes together.
go
type Node struct {
    value int
    next  *Node
}

// Head points to the first node
var head *Node = nil
💻

Example

This example shows how to create a linked list, add nodes to it, and print all values by traversing the list.

go
package main

import "fmt"

type Node struct {
    value int
    next  *Node
}

func main() {
    var head *Node = nil

    // Add nodes to the list
    head = &Node{value: 10, next: nil}
    head.next = &Node{value: 20, next: nil}
    head.next.next = &Node{value: 30, next: nil}

    // Traverse and print
    current := head
    for current != nil {
        fmt.Println(current.value)
        current = current.next
    }
}
Output
10 20 30
⚠️

Common Pitfalls

Common mistakes include:

  • Not initializing the head pointer before adding nodes, causing nil pointer errors.
  • Forgetting to update the next pointer when inserting or deleting nodes.
  • Traversing without checking for nil, leading to runtime panics.

Always check if the list is empty before operations and carefully update pointers to maintain list integrity.

go
package main

import "fmt"

type Node struct {
    value int
    next  *Node
}

func main() {
    var head *Node = nil

    // Wrong: Trying to add node without initializing head
    // head.next = &Node{value: 10} // This will panic

    // Right: Initialize head first
    head = &Node{value: 10, next: nil}
    head.next = &Node{value: 20, next: nil}

    // Traverse safely
    current := head
    for current != nil {
        fmt.Println(current.value)
        current = current.next
    }
}
Output
10 20
📊

Quick Reference

  • Node struct: Holds data and pointer to next node.
  • Head pointer: Start of the list.
  • Adding nodes: Update next pointers carefully.
  • Traversal: Loop until nil pointer.
  • Empty list: Head is nil.

Key Takeaways

Define a Node struct with a value and a pointer to the next node to build a linked list.
Always initialize the head pointer before adding nodes to avoid nil pointer errors.
Traverse the list by following next pointers until you reach nil.
Update next pointers carefully when inserting or deleting nodes to keep the list intact.
Check for nil pointers before accessing nodes to prevent runtime panics.