Mental Model
Count how many nodes are in the linked list by moving from the start to the end one by one.
Analogy: Like counting people in a line by asking each person to point to the next until no one is left.
head -> [1] -> [2] -> [3] -> null
head -> [1] -> [2] -> [3] -> null
head -> [1 ↑] -> [2] -> [3] -> null
head -> [1] -> [2 ↑] -> [3] -> null
head -> [1] -> [2] -> [3 ↑] -> null
head -> [1] -> [2] -> [3] -> null
head -> [1] -> [2] -> [3] -> null Length = 3
package main import "fmt" type Node struct { value int next *Node } func getLength(head *Node) int { count := 0 current := head for current != nil { count++ // increment count for current node current = current.next // move to next node } return count } func main() { // create linked list 1 -> 2 -> 3 -> null node3 := &Node{value: 3, next: nil} node2 := &Node{value: 2, next: node3} head := &Node{value: 1, next: node2} length := getLength(head) fmt.Printf("Length = %d\n", length) }
for current != nil {count++ // increment count for current nodecurrent = current.next // move to next nodefor current != nil {count++ // increment count for current nodetype Node struct {
value int
next *Node
}
func getLength(head *Node) int {
length := 0
current := head
for current != nil {
length++
current = current.next
}
return length
}
// Linked list: 10 -> 20 -> 30 -> nil
head := &Node{10, &Node{20, &Node{30, nil}}}
fmt.Println(getLength(head))func getLength(head *Node) int {
length := 0
for head.next != nil {
length++
head = head.next
}
return length
}func getLength(head *Node) int {
length := 0
current := head
for current != nil {
// Your condition here
current = current.next
}
return length
}Pass the test and this pattern moves unknown