Linked List

A singly linked list with pointer-based nodes supporting Push, Pop, Find, and Print operations. Demonstrates how pointer mechanics work for building dynamic data structures in Go.

package main

import "fmt"

type Node struct {
	Value int
	Next  *Node
}

type LinkedList struct {
	Head *Node
	Size int
}

func (ll *LinkedList) Push(value int) {
	node := &Node{Value: value}
	node.Next = ll.Head
	ll.Head = node
	ll.Size++
}

func (ll *LinkedList) Append(value int) {
	node := &Node{Value: value}
	ll.Size++

	if ll.Head == nil {
		ll.Head = node
		return
	}

	current := ll.Head
	for current.Next != nil {
		current = current.Next
	}
	current.Next = node
}

func (ll *LinkedList) Pop() (int, bool) {
	if ll.Head == nil {
		return 0, false
	}

	value := ll.Head.Value
	ll.Head = ll.Head.Next
	ll.Size--
	return value, true
}

func (ll *LinkedList) Find(value int) *Node {
	current := ll.Head
	for current != nil {
		if current.Value == value {
			return current
		}
		current = current.Next
	}
	return nil
}

func (ll *LinkedList) Reverse() {
	var prev *Node
	current := ll.Head

	for current != nil {
		next := current.Next
		current.Next = prev
		prev = current
		current = next
	}

	ll.Head = prev
}

func (ll *LinkedList) Print(label string) {
	fmt.Printf("%s: ", label)
	current := ll.Head
	for current != nil {
		fmt.Printf("%d", current.Value)
		if current.Next != nil {
			fmt.Print(" -> ")
		}
		current = current.Next
	}
	fmt.Printf(" (size: %d)\n", ll.Size)
}

func main() {
	list := &LinkedList{}

	// Build the list
	list.Append(10)
	list.Append(20)
	list.Append(30)
	list.Push(5)
	list.Print("After build")

	// Find a node
	node := list.Find(20)
	if node != nil {
		fmt.Printf("Found: %d (next: %d)\n", node.Value, node.Next.Value)
	}

	notFound := list.Find(99)
	fmt.Printf("Find 99: %v\n", notFound)

	// Pop from front
	val, ok := list.Pop()
	fmt.Printf("Popped: %d (ok: %v)\n", val, ok)
	list.Print("After pop")

	// Reverse the list
	list.Reverse()
	list.Print("Reversed")

	// Pop until empty
	fmt.Print("Draining: ")
	for {
		v, ok := list.Pop()
		if !ok {
			break
		}
		fmt.Printf("%d ", v)
	}
	fmt.Println()
	list.Print("Empty list")
}
▶ Open Go Playground

Copy the code above and paste to run

© 2026 ByteLearn.dev. Free courses for developers. · Privacy