Mental Model
Count each node one by one until you reach the end of the list.
Analogy: Like counting people standing in a line by moving from the first person to the last one.
head -> 1 -> 2 -> 3 -> null
head -> 1 -> 2 -> 3 -> null
head -> [curr->1] -> 2 -> 3 -> null
head -> 1 -> [curr->2] -> 3 -> null
head -> 1 -> 2 -> [curr->3] -> null
head -> 1 -> 2 -> 3 -> [curr->null]
head -> 1 -> 2 -> 3 -> null Length = 3
class Node: def __init__(self, val): self.val = val self.next = None class LinkedList: def __init__(self): self.head = None def append(self, val): new_node = Node(val) if not self.head: self.head = new_node return curr = self.head while curr.next: curr = curr.next curr.next = new_node def get_length(self): count = 0 curr = self.head while curr: count += 1 # count current node curr = curr.next # move to next node return count # Driver code ll = LinkedList() ll.append(1) ll.append(2) ll.append(3) length = ll.get_length() print(f"Length = {length}")
while curr:count += 1 # count current nodecurr = curr.next # move to next nodewhile curr:while curr: