Introduction
Imagine you have a list of items, like a shopping list, and you want to add new things or remove some you no longer need. Insertion and deletion operations help us manage collections of data by adding or removing elements efficiently.
Think of a row of lockers. Adding a new locker in the middle means shifting all lockers after it to the right to make space, like inserting in an array. But if the lockers are connected by chains, you can just add or remove a locker by changing the chain links, like in a linked list.
Array before insertion: [ A | B | C | D ] Insert 'X' at position 2: [ A | X | B | C | D ] ↑ ↑ Shift elements right Linked list before insertion: A -> B -> C -> D Insert 'X' after A: A -> X -> B -> C -> D ↑ ↑ Change pointers only
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def insert_after(self, prev_node, data): if not prev_node: return new_node = Node(data) new_node.next = prev_node.next prev_node.next = new_node def delete_node(self, key): temp = self.head if temp and temp.data == key: self.head = temp.next temp = None return prev = None while temp and temp.data != key: prev = temp temp = temp.next if temp is None: return prev.next = temp.next temp = None def print_list(self): temp = self.head while temp: print(temp.data, end=' -> ' if temp.next else '\n') temp = temp.next # Create list and perform insertion and deletion ll = LinkedList() ll.head = Node('A') second = Node('B') third = Node('C') ll.head.next = second second.next = third print('Original list:') ll.print_list() ll.insert_after(second, 'X') print('After inserting X after B:') ll.print_list() ll.delete_node('B') print('After deleting B:') ll.print_list()