Concept Flow - Push Using Linked List Node
Create new node with value
Set new node's next to current head
Update head to new node
Done
This flow shows how a new node is created and added at the start of the linked list by adjusting pointers.
func push(head *Node, val int) *Node { newNode := &Node{val, head} return newNode }
| Step | Operation | Nodes in List | Pointer Changes | Visual State |
|---|---|---|---|---|
| 1 | Start with empty list | None | head = nil | null |
| 2 | Create new node with value 10 | 10 -> null | newNode.next = nil | 10 -> null |
| 3 | Set newNode.next to head (nil) | 10 -> null | newNode.next = head (nil) | 10 -> null |
| 4 | Update head to newNode | 10 -> null | head = newNode | 10 -> null |
| 5 | Create new node with value 20 | 20 -> 10 -> null | newNode.next = head (10) | 20 -> 10 -> null |
| 6 | Update head to newNode | 20 -> 10 -> null | head = newNode | 20 -> 10 -> null |
| 7 | Create new node with value 30 | 30 -> 20 -> 10 -> null | newNode.next = head (20) | 30 -> 20 -> 10 -> null |
| 8 | Update head to newNode | 30 -> 20 -> 10 -> null | head = newNode | 30 -> 20 -> 10 -> null |
| 9 | End of push operations | 30 -> 20 -> 10 -> null | head points to 30 | 30 -> 20 -> 10 -> null |
| Variable | Start | After Step 2 | After Step 5 | After Step 7 | Final |
|---|---|---|---|---|---|
| head | nil | 10 | 20 | 30 | 30 |
| newNode | nil | 10 | 20 | 30 | nil |
| newNode.next | nil | nil | 10 | 20 | nil |
Push Using Linked List Node: - Create new node with value - Set new node's next to current head - Update head to new node - New node becomes list start - List grows at front with each push
push operation do in a linked list when using a node?type Node struct {
data int
next *Node
}
func main() {
var head *Node = nil
head = &Node{data: 1, next: head}
head = &Node{data: 2, next: head}
head = &Node{data: 3, next: head}
printList(head)
}
func printList(node *Node) {
for node != nil {
fmt.Print(node.data, " -> ")
node = node.next
}
fmt.Print("null")
}type Node struct {
data int
next *Node
}
func push(head *Node, data int) {
newNode := &Node{data: data, next: head}
head = newNode
}
func main() {
var head *Node = nil
push(head, 10)
// printList(head) expected to show 10 -> null
}Pass the test and this pattern moves unknown