Mental Model
Add a new item at the start by linking it before the current first item and updating pointers.
Analogy: Imagine adding a new book at the front of a shelf where each book knows the one before and after it.
null β 1 β 2 β 3 -> null
null β 1 β 2 β 3 -> null
null β 1 β 2 β 3 -> null, new_node(0)
new_node(0) -> 1 β 2 β 3 -> null
new_node(0) β 1 β 2 β 3 -> null
null β 0 β 1 β 2 β 3 -> null βhead
null β 0 β 1 β 2 β 3 -> null
class Node: def __init__(self, data): self.data = data self.prev = None self.next = None class DoublyLinkedList: def __init__(self): self.head = None def insert_at_beginning(self, data): new_node = Node(data) # create new node if self.head is None: self.head = new_node # empty list, new node is head return new_node.next = self.head # link new node forward to old head self.head.prev = new_node # link old head back to new node self.head = new_node # update head to new node def print_list(self): curr = self.head result = [] while curr: result.append(str(curr.data)) curr = curr.next print(" β ".join(result) + " -> null") # Driver code dll = DoublyLinkedList() dll.insert_at_beginning(3) dll.insert_at_beginning(2) dll.insert_at_beginning(1) # List is now 1 β 2 β 3 # Insert 0 at beginning dll.insert_at_beginning(0) dll.print_list()
new_node = Node(data) # create new nodeif self.head is None:
self.head = new_node # empty list, new node is head
returnnew_node.next = self.head # link new node forward to old headself.head.prev = new_node # link old head back to new nodeself.head = new_node # update head to new nodeif self.head is None: self.head = new_node # empty list, new node is head return
new_node.next = self.head # link new node forward to old head