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
new_node(0) -> null, head -> 1 -> 2 -> 3 -> null
new_node(0) -> 1 -> 2 -> 3 -> null, head -> 1 -> 2 -> 3 -> null
head -> 0 -> 1 -> 2 -> 3 -> null
head -> 0 -> 1 -> 2 -> 3 -> null
class Node: def __init__(self, val): self.val = val self.next = None class LinkedList: def __init__(self): self.head = None def insert_at_beginning(self, val): new_node = Node(val) # create new node new_node.next = self.head # link new node to current head self.head = new_node # update head to new node def __str__(self): result = [] curr = self.head while curr: result.append(str(curr.val)) curr = curr.next return ' -> '.join(result) + ' -> null' # Driver code ll = LinkedList() ll.insert_at_beginning(3) ll.insert_at_beginning(2) ll.insert_at_beginning(1) print("Before insertion:", ll) ll.insert_at_beginning(0) print("After insertion:", ll)
new_node = Node(val) # create new nodenew_node.next = self.head # link new node to current headself.head = new_node # update head to new nodenew_node.next = self.head # link new node to current headself.head = new_node # update head to new node