Build linked lists and ring buffers
Build linked lists and ring buffers
A singly linked list stores each value with a pointer to the next node. Inserting at the head costs constant work, but finding an arbitrary index requires traversal. A ring buffer instead reuses a fixed array: the logical front advances modulo capacity, so elements need not shift.
package main
import ( "fmt")
type Node struct { Value int Next *Node}
func prepend(head *Node, v int) *Node { return &Node{Value: v, Next: head} }func main() { var head *Node head = prepend(head, 2) head = prepend(head, 1) for n := head; n != nil; n = n.Next { fmt.Println(n.Value) }}Each new node points to the previous head. nil marks the end. Traversal assumes an acyclic chain; accidentally linking a node to itself creates a cycle. The head pointer is returned explicitly. Linked nodes allow local insertion without shifting, but pointer chasing and allocation can cost more than contiguous storage.
Expected output:
12Use a bounded ring queue
package main
import ( "fmt")
type Ring struct { data [3]int head, n int}
func (r *Ring) Push(v int) bool { if r.n == len(r.data) { return false } r.data[(r.head+r.n)%len(r.data)] = v r.n++ return true}func (r *Ring) Pop() (int, bool) { if r.n == 0 { return 0, false } v := r.data[r.head] r.data[r.head] = 0 r.head = (r.head + 1) % len(r.data) r.n-- return v, true}func main() { var r Ring fmt.Println(r.Push(1), r.Push(2), r.Push(3), r.Push(4)) fmt.Println(r.Pop()) fmt.Println(r.Push(4)) fmt.Println(r.Pop()) fmt.Println(r.Pop()) fmt.Println(r.Pop()) fmt.Println(r.Pop())}head is the index of the oldest item; n is the occupied count from 0 to 3. The next insertion index is (head+n)%capacity. Full means reject rather than overwrite; empty means return false. Both operations are O(1). A positive capacity is required for modulo; here [3]int guarantees it. This is not a concurrent queue.
Expected output:
true true true false1 truetrue2 true3 true4 true0 falseTry it locally
Build a three-node singly linked list with prepend, then count its nodes by traversal. Print the count for a nil head as well.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Data structures 02: Build linked lists and ring buffers
Check the lesson objective before moving on.
How does a ring buffer wrap its index?
What distinguishes full from empty in this ring?