How to Implement a Linked List in Go

Define a Node struct with a Next pointer and implement Append and Print methods to manage the chain.

Implement a linked list in Go by defining a Node struct with a value and a pointer to the next node, then creating methods to append and print the list.

package main

import "fmt"

type Node struct {
	Value int
	Next  *Node
}

func (l *Node) Append(value int) {
	curr := l
	for curr.Next != nil {
		curr = curr.Next
	}
	curr.Next = &Node{Value: value}
}

func (l *Node) Print() {
	for curr := l; curr != nil; curr = curr.Next {
		fmt.Print(curr.Value, " ")
	}
	fmt.Println()
}

func main() {
	head := &Node{Value: 1}
	head.Append(2)
	head.Append(3)
	head.Print()
}