Linked Structures
Build a Singly Linked List
Construct a singly linked list by allocating one node per value and
chaining next references. Establishes the node + head + tail model used
by every later linked-list lesson.
Algorithm
Canonical input [10, 20, 30, 40] builds the chain
head -> 10 -> 20 -> 30 -> 40 -> nil with one node appended per step.
Basic Implementation
basic.go
package main
import "fmt"
type ListNode struct {
Value int
Next *ListNode
}
func main() {
values := []int{10, 20, 30, 40}
var head *ListNode = nil
var tail *ListNode = nil
for i := 0; i < len(values); i++ {
node := &ListNode{Value: values[i], Next: nil}
if head == nil {
head = node
} else {
tail.Next = node
}
tail = node
}
for cur := head; cur != nil; cur = cur.Next {
fmt.Printf("%d -> ", cur.Value)
}
fmt.Println("nil")
}
Complexity
- Time: O(n) with a tail pointer
- Space: O(n) for the chain
Implementation notes
- Go: a small
type ListNode struct { Value int; Next *ListNode }pattern is the idiomatic Node.nilrepresents end-of-list honestly. - The replay never shows runtime pointer addresses; nodes are labelled
node(<value>)and the chain view is rendered as10 -> 20 -> ... -> nil. - Go's garbage collector reclaims the chain when it falls out of scope, so the build step stays focused on wiring without an explicit free walk.
node chain
Each `ListNode` carries an `int Value` and a `*ListNode` `Next` pointer.