Concept Flow - Insert at Beginning Head Insert
Create new node
New node.next = head
head = new node
Done: new node is new head
Insert a new node by making it point to the current head, then update head to this new node.
func InsertAtBeginning(head *Node, val int) *Node { newNode := &Node{data: val} newNode.next = head head = newNode return head }
| Step | Operation | Nodes in List | Pointer Changes | Visual State |
|---|---|---|---|---|
| 1 | Start with list 10 -> 20 -> 30 -> null | 10 -> 20 -> 30 -> null | head points to node with 10 | āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā ā data:10ā ā data:20ā ā data:30ā ā next:āāā¼āāā ā next:āāā¼āāā ā next:ā ā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā head |
| 2 | Create new node with data 5 | 10 -> 20 -> 30 -> null | newNode created with data 5, next = null | newNode: āāāāāāāāāā ā data:5 ā ā next:ā ā āāāāāāāāāā |
| 3 | Set newNode.next = head | 10 -> 20 -> 30 -> null | newNode.next points to node with 10 | newNode: āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā ā data:5 āāāā ā data:10āāāā ā data:20āāāā ā data:30ā ā next:āāā¼ ā next:āāā¼ ā next:āāā¼ ā next:ā ā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā |
| 4 | Update head = newNode | 5 -> 10 -> 20 -> 30 -> null | head points to newNode with data 5 | āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā ā data:5 āāāā ā data:10āāāā ā data:20āāāā ā data:30ā ā next:āāā¼ ā next:āāā¼ ā next:āāā¼ ā next:ā ā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā head |
| 5 | Return new head | 5 -> 10 -> 20 -> 30 -> null | head unchanged | Final list: āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā ā data:5 āāāā ā data:10āāāā ā data:20āāāā ā data:30ā ā next:āāā¼ ā next:āāā¼ ā next:āāā¼ ā next:ā ā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā āāāāāāāāāā head |
| Variable | Start | After Step 2 | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|---|
| head | points to node 10 | points to node 10 | points to node 10 | points to newNode (5) | points to newNode (5) |
| newNode | nil | points to node 5 (next=null) | points to node 5 (next=10) | points to node 5 (next=10) | points to node 5 (next=10) |
| List Nodes | 10 -> 20 -> 30 -> null | 10 -> 20 -> 30 -> null | 5 -> 10 -> 20 -> 30 -> null (newNode linked) | 5 -> 10 -> 20 -> 30 -> null | 5 -> 10 -> 20 -> 30 -> null |
Insert at Beginning (Head Insert): - Create new node with data - Set newNode.next = current head - Update head = newNode - New node becomes first element - Works even if list is empty
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