Level: BeginnerGo Programs

Go Linked List Programs: Reverse, Middle, Cycle and Merge

Updated 23 min read
Go Linked List Programs featured image: reverse, middle and cycle output

Go linked list programs are one of the most asked topics in coding interviews, because they test pointers, loops and careful thinking all at once. In this post, you will write fourteen programs with their exact output and the logic explained in comments, covering insert, delete, search, reverse, middle node, cycle check, merge and a generic list.

You should first finish our Go struct programs and Go pointer programs, because every node is a struct linked by a pointer. The Go generics programs help with the last program. All programs were tested on Go 1.27.

What are Go Linked List Programs?

Go linked list programs build a chain of nodes. Each node holds a value and a pointer to the next node. The first node is called the head, and the last node points to nil.

Think of a treasure hunt. Each clue tells you where the next clue is hidden. You cannot jump to clue five, so you follow the clues one by one from the start. A linked list works the same way.

Why Go Linked List Programs Matter

Slices are the normal choice in Go, so you may wonder why lists matter. There are four good reasons.

  • Interviews: reverse a list, find the middle and detect a cycle are asked in almost every round.
  • Fast insert and delete: adding a node at the front takes the same time for 10 or 10 million nodes.
  • Real systems: LRU caches, undo history and task queues often use linked lists inside.
  • Pointer practice: these programs make you really understand how pointers work.

How Go Linked List Programs Work

Every program in this post uses the same Node type. A node has a Value field and a Next field that points to another node. To walk the list, you start at the head and follow Next until you reach nil.

Go linked list programs diagram showing head node, next pointers and nil at the end
Each node stores a value and a pointer to the next node, and the last node points to nil.

The table below shows the cost of common list operations.

OperationLinked listSlice
Read item at index iO(n), walk from headO(1)
Insert at the frontO(1)O(n), shifts items
Insert at the endO(n), or O(1) with a tail pointerO(1) on average
Delete a known nodeO(1) after you find itO(n)
Memory per itemValue plus a pointerValue only

Basic Go Linked List Programs

These first Go linked list programs build a list, print it, add nodes, remove nodes and search for a value.

package main

import "fmt"

// Node is one box in the chain. It holds a number and a link to the next box.
type Node struct {
    Value int   // the number stored in this node
    Next  *Node // *Node means "address of a Node"; nil means no next node
}

func main() {
    // Step 1: make three separate nodes.
    first := &Node{Value: 10} // := creates a variable; & gives the address of the new node
    second := &Node{Value: 20}
    third := &Node{Value: 30}

    // Step 2: link them into a chain.
    first.Next = second
    second.Next = third // third.Next stays nil, so the chain ends here

    // Step 3: read the values by following the links.
    fmt.Println(first.Value)
    fmt.Println(first.Next.Value)      // one hop: first -> second
    fmt.Println(first.Next.Next.Value) // two hops: first -> second -> third
    fmt.Println(third.Next == nil)     // nil means "points to nothing"
}
10
20
30
true

This is the smallest possible linked list. First you create three nodes, and then you set each Next field to the following node. To reach the third value, you start at first and follow Next twice.

Program 2: Build and Print a Linked List

package main

import "fmt"

// Node is one item in the list.
type Node struct {
    Value int
    Next  *Node // pointer to the next node, nil at the end
}

// printList walks from the head to nil and prints each value.
func printList(head *Node) {
    current := head // start at the first node
    for current != nil {
        fmt.Print(current.Value, " -> ")
        current = current.Next // move one node forward
    }
    fmt.Println("nil")
}

// fromSlice builds a list in the same order as the slice.
func fromSlice(values []int) *Node {
    var head *Node // first node, nil while the list is empty
    var tail *Node // last node, so we can add after it quickly
    for _, value := range values { // range gives each item; _ skips the index
        newNode := &Node{Value: value}
        if head == nil {
            head = newNode // the first node becomes the head
        } else {
            tail.Next = newNode // link the old tail to the new node
        }
        tail = newNode // the new node is now the last one
    }
    return head
}

func main() {
    head := fromSlice([]int{10, 20, 30})
    printList(head)
}
10 -> 20 -> 30 -> nil

The fromSlice function keeps a tail pointer while it builds, so each new node is linked in one step. Without it, you would walk the whole list for every insert. Then printList moves current forward until it becomes nil.

Program 3: Insert at the Head, Tail and a Position

package main

import "fmt"

// Node is one item in the list.
type Node struct {
    Value int
    Next  *Node
}

// printList prints every value from the head to the end.
func printList(head *Node) {
    current := head
    for current != nil {
        fmt.Print(current.Value, " -> ")
        current = current.Next
    }
    fmt.Println("nil")
}

// pushFront adds a node before the head and returns the new head.
func pushFront(head *Node, value int) *Node {
    return &Node{Value: value, Next: head} // the new node points to the old head
}

// pushBack walks to the last node and links a new one after it.
func pushBack(head *Node, value int) *Node {
    newNode := &Node{Value: value}
    if head == nil {
        return newNode // empty list: the new node is the whole list
    }
    current := head
    for current.Next != nil {
        current = current.Next // stop at the last node
    }
    current.Next = newNode
    return head
}

// insertAt puts value at the given position (0 means the front).
func insertAt(head *Node, position int, value int) *Node {
    if position == 0 {
        return pushFront(head, value)
    }
    // Step 1: walk to the node just before the position.
    current := head
    for i := 0; i < position-1 && current != nil; i++ {
        current = current.Next
    }
    if current == nil {
        return head // the position is past the end, so do nothing
    }
    // Step 2: the new node points to whatever came after current.
    newNode := &Node{Value: value, Next: current.Next}
    // Step 3: current now points to the new node.
    current.Next = newNode
    return head
}

func main() {
    var head *Node // an empty list
    head = pushBack(head, 2)
    head = pushBack(head, 4)
    head = pushFront(head, 1)
    head = insertAt(head, 2, 3)
    printList(head)
}
1 -> 2 -> 3 -> 4 -> nil

Each function returns the head, because adding at the front changes which node is first. Always assign the result back, as in head = pushFront(head, 1). For insertAt, you stop one node early, link the new node to the rest, and then link the earlier node to it.

Program 4: Delete a Node by Value

package main

import "fmt"

// Node is one item in the list.
type Node struct {
    Value int
    Next  *Node
}

// printList prints every value from the head to the end.
func printList(head *Node) {
    current := head
    for current != nil {
        fmt.Print(current.Value, " -> ")
        current = current.Next
    }
    fmt.Println("nil")
}

// deleteValue removes the first node that holds target.
func deleteValue(head *Node, target int) *Node {
    dummy := &Node{Next: head} // a fake node before the head keeps the logic simple
    previous := dummy
    for previous.Next != nil {
        if previous.Next.Value == target {
            previous.Next = previous.Next.Next // skip over the node to remove it
            break                              // stop after the first match
        }
        previous = previous.Next
    }
    return dummy.Next // the real head, which may have changed
}

func main() {
    head := &Node{1, &Node{2, &Node{3, nil}}} // builds 1 -> 2 -> 3 by nesting nodes
    head = deleteValue(head, 2)
    printList(head)
    head = deleteValue(head, 1) // deleting the head works the same way
    printList(head)
}
1 -> 3 -> nil
3 -> nil

The loop always looks one node ahead with previous.Next. When it finds the target, it links previous straight to the node after the target. The dummy node trick means you never need a special case for deleting the head. Interviewers like to see it.

Program 5: Search a Linked List for a Value

package main

import "fmt"

// Node is one item in the list.
type Node struct {
    Value int
    Next  *Node
}

// findIndex returns the position of target, or -1 if it is not in the list.
func findIndex(head *Node, target int) int {
    index := 0
    current := head
    for current != nil {
        if current.Value == target {
            return index // found it, so stop here
        }
        current = current.Next
        index++
    }
    return -1 // we reached nil without finding the value
}

func main() {
    head := &Node{10, &Node{20, &Node{30, &Node{40, nil}}}}
    fmt.Println("index of 30:", findIndex(head, 30))
    fmt.Println("index of 99:", findIndex(head, 99))
}
index of 30: 2
index of 99: -1

You walk the list one node at a time and count the steps in index. If a node holds the target, you return the count right away. If you reach nil first, the value is missing, so you return -1.

Most Asked Interview Go Linked List Programs

These Go linked list programs are the ones you will meet again and again in coding rounds.

Program 6: Reverse a Linked List

package main

import "fmt"

// Node is one item in the list.
type Node struct {
    Value int
    Next  *Node
}

// printList prints every value from the head to the end.
func printList(head *Node) {
    current := head
    for current != nil {
        fmt.Print(current.Value, " -> ")
        current = current.Next
    }
    fmt.Println("nil")
}

// reverse flips every Next pointer using three pointers: prev, cur and next.
func reverse(head *Node) *Node {
    var prev *Node // the reversed part starts empty
    cur := head    // the node we are working on now
    for cur != nil {
        next := cur.Next // Step 1: remember the rest of the list
        cur.Next = prev  // Step 2: point this node backwards
        prev = cur       // Step 3: move prev forward
        cur = next       // Step 4: move cur forward
    }
    return prev // prev is the old last node, now the head
}

func main() {
    head := &Node{1, &Node{2, &Node{3, &Node{4, nil}}}}
    printList(reverse(head))
}
4 -> 3 -> 2 -> 1 -> nil

In Go linked list programs, this is the question asked most. You save next first, because changing cur.Next would lose the rest of the list. The four steps run once per node, so this is O(n) time and O(1) extra memory. Draw the boxes on paper the first few times.

Go linked list programs reverse steps with prev, cur and next pointers
Each step saves next, turns cur.Next back to prev, then moves both pointers one node forward.

Program 7: Find the Middle Node with Slow and Fast Pointers

package main

import "fmt"

// Node is one item in the list.
type Node struct {
    Value int
    Next  *Node
}

// fromSlice builds a list in the same order as the slice.
func fromSlice(values []int) *Node {
    dummy := &Node{} // a fake first node, so we never check for an empty list
    tail := dummy
    for _, value := range values {
        tail.Next = &Node{Value: value}
        tail = tail.Next
    }
    return dummy.Next // skip the fake node
}

// middle moves slow one step and fast two steps.
// When fast reaches the end, slow is in the middle.
func middle(head *Node) *Node {
    slow := head
    fast := head
    for fast != nil && fast.Next != nil {
        slow = slow.Next      // one step
        fast = fast.Next.Next // two steps
    }
    return slow
}

func main() {
    oddList := fromSlice([]int{1, 2, 3, 4, 5})
    evenList := fromSlice([]int{1, 2, 3, 4, 5, 6})
    fmt.Println(middle(oddList).Value)
    fmt.Println(middle(evenList).Value) // even length: second middle
}
3
4

The fast pointer moves twice as quickly as slow. So when fast reaches the end, slow has covered half the list. This finds the middle in one pass, without counting the length first. For an even length, it returns the second of the two middle nodes.

Program 8: Detect a Cycle (Floyd’s Method)

package main

import "fmt"

// Node is one item in the list.
type Node struct {
    Value int
    Next  *Node
}

// hasCycle reports true if fast ever meets slow, which means the list loops.
func hasCycle(head *Node) bool {
    slow := head
    fast := head
    for fast != nil && fast.Next != nil {
        slow = slow.Next
        fast = fast.Next.Next
        if slow == fast { // compare pointers (same node), not values
            return true
        }
    }
    return false // fast reached nil, so the list has an end
}

func main() {
    first := &Node{Value: 1}
    second := &Node{Value: 2}
    third := &Node{Value: 3}
    first.Next = second
    second.Next = third
    fmt.Println("cycle:", hasCycle(first))

    third.Next = first // the last node now points back to the first
    fmt.Println("cycle:", hasCycle(first))
}
cycle: false
cycle: true

If the list has an end, fast reaches nil and the function returns false. Inside a loop, the fast pointer gains one node on the slow pointer each step, so it must catch up. This needs no extra map, so memory stays O(1).

Program 9: Merge Two Sorted Lists

package main

import "fmt"

// Node is one item in the list.
type Node struct {
    Value int
    Next  *Node
}

// fromSlice builds a list in the same order as the slice.
func fromSlice(values []int) *Node {
    dummy := &Node{}
    tail := dummy
    for _, value := range values {
        tail.Next = &Node{Value: value}
        tail = tail.Next
    }
    return dummy.Next
}

// printList prints every value from the head to the end.
func printList(head *Node) {
    for current := head; current != nil; current = current.Next {
        fmt.Print(current.Value, " -> ")
    }
    fmt.Println("nil")
}

// merge picks the smaller front node each time and links it to the result.
func merge(first, second *Node) *Node {
    dummy := &Node{}
    tail := dummy // last node of the merged list
    for first != nil && second != nil {
        if first.Value <= second.Value {
            tail.Next = first   // take the node from the first list
            first = first.Next  // move along the first list
        } else {
            tail.Next = second  // take the node from the second list
            second = second.Next
        }
        tail = tail.Next
    }
    if first != nil { // one list may still have nodes left
        tail.Next = first
    } else {
        tail.Next = second
    }
    return dummy.Next
}

func main() {
    listA := fromSlice([]int{1, 4, 7})
    listB := fromSlice([]int{2, 3, 8, 9})
    printList(merge(listA, listB))
}
1 -> 2 -> 3 -> 4 -> 7 -> 8 -> 9 -> nil

Each round compares the front of both lists and moves the smaller node to the result. When one list runs out, the other list is already sorted, so you attach it in one step. No new nodes are created, so the merge uses O(1) extra memory.

Program 10: Remove the Nth Node from the End

package main

import "fmt"

// Node is one item in the list.
type Node struct {
    Value int
    Next  *Node
}

// fromSlice builds a list in the same order as the slice.
func fromSlice(values []int) *Node {
    dummy := &Node{}
    tail := dummy
    for _, value := range values {
        tail.Next = &Node{Value: value}
        tail = tail.Next
    }
    return dummy.Next
}

// printList prints every value from the head to the end.
func printList(head *Node) {
    for current := head; current != nil; current = current.Next {
        fmt.Print(current.Value, " -> ")
    }
    fmt.Println("nil")
}

// removeFromEnd removes the node that is stepsFromEnd places from the end.
func removeFromEnd(head *Node, stepsFromEnd int) *Node {
    dummy := &Node{Next: head}
    fast := dummy
    slow := dummy
    // Step 1: move fast ahead to make a gap between the two pointers.
    for i := 0; i <= stepsFromEnd; i++ {
        fast = fast.Next
    }
    // Step 2: move both pointers together until fast falls off the end.
    for fast != nil {
        fast = fast.Next
        slow = slow.Next
    }
    // Step 3: slow is just before the target, so skip the target.
    slow.Next = slow.Next.Next
    return dummy.Next
}

func main() {
    head := fromSlice([]int{1, 2, 3, 4, 5})
    printList(removeFromEnd(head, 2))
}
1 -> 2 -> 3 -> 5 -> nil

First, fast moves ahead to open a fixed gap. Then both pointers move together, so the gap stays the same. When fast falls off the end, slow sits right before the node to remove. Again, the dummy node handles the case where the head itself is removed.

Program 11: Check if a List is a Palindrome

package main

import "fmt"

// Node is one item in the list.
type Node struct {
    Value int
    Next  *Node
}

// fromSlice builds a list in the same order as the slice.
func fromSlice(values []int) *Node {
    dummy := &Node{}
    tail := dummy
    for _, value := range values {
        tail.Next = &Node{Value: value}
        tail = tail.Next
    }
    return dummy.Next
}

// reverse flips the list one node at a time and returns the new head.
func reverse(head *Node) *Node {
    var previous *Node
    current := head
    for current != nil {
        nextNode := current.Next // Step 1: save the rest of the list
        current.Next = previous  // Step 2: point this node backwards
        previous = current       // Step 3: move previous forward
        current = nextNode       // Step 4: move current forward
    }
    return previous
}

// isPalindrome finds the middle, reverses the second half, then compares.
func isPalindrome(head *Node) bool {
    slow := head
    fast := head
    for fast != nil && fast.Next != nil {
        slow = slow.Next
        fast = fast.Next.Next
    }
    firstHalf := head
    secondHalf := reverse(slow) // slow is at the middle
    for secondHalf != nil {
        if firstHalf.Value != secondHalf.Value {
            return false
        }
        firstHalf = firstHalf.Next
        secondHalf = secondHalf.Next
    }
    return true
}

func main() {
    fmt.Println(isPalindrome(fromSlice([]int{1, 2, 3, 2, 1})))
    fmt.Println(isPalindrome(fromSlice([]int{1, 2, 3, 4})))
}
true
false

First, slow and fast pointers find the middle. Next, you reverse the second half, so it reads from the end back to the middle. Finally, you compare both halves node by node. Combining small tricks like this is how most list questions are solved.

Other Kinds of Go Linked List Programs

So far every node pointed only forward. The next Go linked list programs add a backward pointer, use the standard library and make the list generic.

Program 12: A Doubly Linked List

package main

import "fmt"

// DNode is a node that points both forward (Next) and backward (Prev).
type DNode struct {
    Value string
    Prev  *DNode
    Next  *DNode
}

// DList keeps track of both ends of a doubly linked list.
type DList struct {
    head *DNode
    tail *DNode
}

// PushBack links a new node after the current tail.
func (list *DList) PushBack(value string) {
    newNode := &DNode{Value: value, Prev: list.tail} // it points back to the old tail
    if list.tail == nil {
        list.head = newNode // empty list: the new node is head and tail
    } else {
        list.tail.Next = newNode
    }
    list.tail = newNode
}

func main() {
    var history DList // the zero value is an empty list
    for _, page := range []string{"home", "search", "product"} {
        history.PushBack(page)
    }
    for node := history.head; node != nil; node = node.Next {
        fmt.Print(node.Value, " ")
    }
    fmt.Println()
    for node := history.tail; node != nil; node = node.Prev { // walk backwards, like a Back button
        fmt.Print(node.Value, " ")
    }
    fmt.Println()
}
home search product
product search home

Each new node points back to the old tail, and the old tail points forward to it. The first loop follows Next from the head. The second loop follows Prev from the tail, so the pages print in reverse. Browser history works like this.

Program 13: Use container/list from the Standard Library

package main

import (
    "container/list"
    "fmt"
)

func main() {
    letters := list.New() // a ready-made doubly linked list
    letters.PushBack("b")
    letters.PushBack("c")
    front := letters.PushFront("a") // returns the element, so we can use it later
    letters.InsertAfter("a2", front)

    for element := letters.Front(); element != nil; element = element.Next() {
        fmt.Print(element.Value, " ")
    }
    fmt.Println("| len:", letters.Len())

    letters.Remove(front) // O(1) because we already hold the element
    fmt.Println("front now:", letters.Front().Value)
}
a a2 b c | len: 4
front now: a2

Here list.New gives you a doubly linked list, so you do not write any node code. You add items with PushBack, PushFront and InsertAfter, then walk it with Front and Next. container/list stores values as any, so you need a type assertion like element.Value.(string) to get a string back.

Program 14: A Generic Linked List

package main

import "fmt"

// node holds one value of any type T.
type node[T any] struct {
    value T
    next  *node[T]
}

// List[T] works for any type T, with a size counter.
type List[T any] struct {
    head *node[T]
    size int
}

// Push adds a value at the front in O(1).
func (list *List[T]) Push(value T) {
    list.head = &node[T]{value: value, next: list.head}
    list.size++
}

// Values returns the items from head to tail as a slice.
func (list *List[T]) Values() []T {
    result := make([]T, 0, list.size) // make creates an empty slice with room for size items
    for current := list.head; current != nil; current = current.next {
        result = append(result, current.value) // append adds to the end of the slice
    }
    return result
}

func main() {
    var numbers List[int] // T is int here
    numbers.Push(3)
    numbers.Push(2)
    numbers.Push(1)

    var names List[string] // T is string here
    names.Push("ravi")
    names.Push("asha")

    fmt.Println(numbers.Values(), numbers.size)
    fmt.Println(names.Values(), names.size)
}
[1 2 3] 3
[asha ravi] 2

The [T any] part means the list can hold any type. You write the code once, then use List[int] and List[string] with full type safety. Keeping a size field makes the length O(1), so you never walk the list to count nodes.

Linked List vs Slice in Go Linked List Programs

Both store a sequence of items, but they are good at different things. The table below compares them.

FeatureLinked listSlice
Memory layoutNodes spread out in memoryOne block of memory
Read by indexSlow, walk from headInstant
Insert at frontInstantSlow, shifts every item
CPU cache usePoorVery good
Extra memoryOne or two pointers per nodeSome spare capacity

A simple rule helps. In real Go code, start with a slice. Use a linked list when you insert and remove in the middle often, or when an interviewer asks for one.

Common Mistakes in Go Linked List Programs

  • Losing the rest of the list: save next := cur.Next before changing cur.Next.
  • Not returning the new head: functions that change the front must return it.
  • Nil pointer panics: check fast != nil && fast.Next != nil before fast.Next.Next.
  • Comparing values instead of pointers: cycle checks must compare nodes, not Value.
  • Special-casing the head: use a dummy node to remove that extra code.

Best Practices for Go Linked List Programs

  • Draw boxes and arrows before writing code, and update them after each line.
  • Use a dummy node for insert, delete and merge.
  • Test small cases: an empty list, one node and two nodes.
  • Keep a tail pointer and size when you add at the end or need the length often.
  • Prefer slices in production code unless you have a clear reason for a list.

Go Linked List Programs Interview Questions and Answers

These are the list questions interviewers ask most, and they build on the Go linked list programs above. Each code answer is complete, with real output from Go 1.27.

Concept Questions on Go Linked List Programs

Q1. What is the time to find the 5th node of a linked list?

It is O(n), because you must start at the head and follow Next four times. A slice gives you numbers[4] in O(1).

Q2. What is the difference between a singly and a doubly linked list?

A singly linked node has only Next. A doubly linked node has Prev and Next, so you can walk both ways. You can also delete a node in O(1), at the cost of one more pointer per node.

Q3. Why does Floyd’s cycle check always work?

Inside a loop, the fast pointer moves one node closer to the slow pointer on every step. So the gap shrinks by one each time and must reach zero, which means they meet.

Q4. What does this program print?

package main

import "fmt"

// Node is one item in the list.
type Node struct {
    Value int
    Next  *Node
}

func main() {
    var head *Node // an empty list is just a nil pointer
    fmt.Println(head == nil)
    head = &Node{Value: 5}
    fmt.Println(head.Next == nil, head.Value)
}
true
true 5

An empty list is a nil head. A single node has a nil Next, which marks the end.

Q5. What happens if you read Value from a nil node?

package main

import "fmt"

// Node is one item in the list.
type Node struct {
    Value int
    Next  *Node
}

func main() {
    head := &Node{Value: 1}
    fmt.Println(head.Next.Value) // head.Next is nil, so this panics
}
panic: runtime error: invalid memory address or nil pointer dereference

This is the most common bug in Go linked list programs. Always check for nil before you follow a pointer.

Coding Questions

Q6. How do you count the nodes in a list?

package main

import "fmt"

// Node is one item in the list.
type Node struct {
    Value int
    Next  *Node
}

// length walks the list once and counts each node.
func length(head *Node) int {
    count := 0
    for current := head; current != nil; current = current.Next {
        count++
    }
    return count
}

func main() {
    head := &Node{1, &Node{2, &Node{3, nil}}}
    fmt.Println(length(head), length(nil))
}
3 0

The loop adds one for each node and stops at nil. So an empty list returns 0 without any special code.

Q7. How do you reverse a list with recursion?

package main

import "fmt"

// Node is one item in the list.
type Node struct {
    Value int
    Next  *Node
}

// reverseRecursive reverses the rest, then hooks the current node on the end.
func reverseRecursive(head *Node) *Node {
    if head == nil || head.Next == nil {
        return head // base case: 0 or 1 node is already reversed
    }
    newHead := reverseRecursive(head.Next) // Step 1: reverse everything after head
    head.Next.Next = head                  // Step 2: the next node now points back to head
    head.Next = nil                        // Step 3: head becomes the new last node
    return newHead
}

func main() {
    head := &Node{1, &Node{2, &Node{3, nil}}}
    for current := reverseRecursive(head); current != nil; current = current.Next {
        fmt.Print(current.Value, " ")
    }
    fmt.Println()
}
3 2 1

The function calls itself on a shorter list each time, until only one node is left. On the way back, each node is hooked behind the node that came after it. This is short, but it uses O(n) stack memory. For very long lists, the loop version from Program 6 is safer.

Q8. How do you remove duplicates from a sorted list?

package main

import "fmt"

// Node is one item in the list.
type Node struct {
    Value int
    Next  *Node
}

// removeDuplicates skips any next node with the same value as the current one.
func removeDuplicates(head *Node) *Node {
    current := head
    for current != nil && current.Next != nil {
        if current.Value == current.Next.Value {
            current.Next = current.Next.Next // drop the duplicate, stay on current
        } else {
            current = current.Next
        }
    }
    return head
}

func main() {
    head := &Node{1, &Node{1, &Node{2, &Node{3, &Node{3, nil}}}}}
    for current := removeDuplicates(head); current != nil; current = current.Next {
        fmt.Print(current.Value, " ")
    }
    fmt.Println()
}
1 2 3

Because the list is sorted, duplicates sit next to each other. When the next node matches, you skip it and stay in place. That is why one pass is enough.

Design Questions

Q9. When would you choose a linked list over a slice in Go?

Choose a list when you often insert or remove items in the middle and already hold a pointer to the spot. An LRU cache is the classic case. For almost everything else, a slice is faster.

Q10. Why does an LRU cache use a doubly linked list and a map?

The map finds a node in O(1), and the doubly linked list moves that node to the front or removes the oldest one in O(1). Together, every operation is O(1). We build one in a later post in this series.

Practice Task

To practise Go linked list programs, write a function that adds two numbers stored as lists in reverse order. For example, 342 is 2 -> 4 -> 3 and 465 is 5 -> 6 -> 4, and the answer 807 is 7 -> 0 -> 8. Hint: walk both lists together and keep a carry value.

Official Resources

Quick Recap

  • Go linked list programs chain nodes together with a Next pointer and end at nil.
  • Reverse a list with three pointers: prev, cur and next.
  • Slow and fast pointers find the middle and detect cycles.
  • A dummy node removes special cases for the head.
  • container/list gives a ready doubly linked list, and generics make a type-safe one.

What’s Next?

Next, we build two data structures that sit on top of lists and slices. Read Go stack and queue programs, with valid parentheses, a min stack and a circular queue. For more pointer practice, revisit the Go pointer programs.