Mental Model
Add a new item right at the start so it becomes the first thing in the list.
Analogy: Imagine putting a new book on the front of a line of books on a shelf, pushing the others back.
head -> 1 -> 2 -> 3 -> null
head -> 1 -> 2 -> 3 -> null
newNode(0) -> null head -> 1 -> 2 -> 3 -> null
newNode(0) -> 1 -> 2 -> 3 -> null head -> 1 -> 2 -> 3 -> null
head -> 0 -> 1 -> 2 -> 3 -> null
head -> 0 -> 1 -> 2 -> 3 -> null
package main import "fmt" type Node struct { value int next *Node } type LinkedList struct { head *Node } func (ll *LinkedList) InsertAtBeginning(val int) { newNode := &Node{value: val} newNode.next = ll.head // link new node to old head ll.head = newNode // update head to new node } func (ll *LinkedList) PrintList() { curr := ll.head for curr != nil { fmt.Printf("%d -> ", curr.value) curr = curr.next } fmt.Println("null") } func main() { ll := &LinkedList{} // create initial list 1 -> 2 -> 3 -> null ll.InsertAtBeginning(3) ll.InsertAtBeginning(2) ll.InsertAtBeginning(1) // insert 0 at beginning ll.InsertAtBeginning(0) ll.PrintList() }
newNode := &Node{value: val}newNode.next = ll.head // link new node to old headll.head = newNode // update head to new nodell.head = newNode // update head to new node
newNode.next = ll.head // link new node to old head
package main
import "fmt"
type Node struct {
data int
next *Node
}
func main() {
head := &Node{data: 5, next: nil}
newNode := &Node{data: 3, next: head}
head = newNode
newNode2 := &Node{data: 1, next: head}
head = newNode2
// Print list
current := head
for current != nil {
fmt.Print(current.data, " -> ")
current = current.next
}
fmt.Print("null")
}type Node struct {
data int
next *Node
}
func insertAtBeginning(head *Node, val int) *Node {
newNode := &Node{data: val}
newNode.next = head.next
head = newNode
return head
}Pass the test and this pattern moves unknown