Python Singlylinked list Element insertion Consider the foll
[Python] [Singly-linked list] [Element insertion] Consider the following singly linked list.
Provide the instructions to insert the new node immediately following the node containing 52. Do not use a loop or any additional external references.
Solution
 
 # Node class
 class Node:
 
 # Function to initialise the node object
 def __init__(self, data):
 self.data = data # Assign data
 self.next = None # Initialize next as null
 
class LinkedList:
 
 # constructor to initialize head
 def __init__(self):
 self.head = None
 
 
 # Function to insert a new node at the beginning
 def push(self, new_data):
 new_node = Node(new_data)
 new_node.next = self.head
 self.head = new_node
 def insert_After(self, prev_node, new_data):
 
 # check if given prev_node exists
 if prev_node is None:
 print \"previous node not in the LinkedList.\"
 return
 
 # create new node and put the data
 new_node = Node(new_data)
 
   
 new_node.next = prev_node.next
 prev_node.next = new_node
 #function to print the linked list
 def print_the_List(self):
 temp = self.head
 while (temp):
 print temp.data,
 temp = temp.next
 
 
 
 # Code execution starts
 if __name__==\'__main__\':
 
 # Start with the empty list
 list = LinkedList()
 
 
 
 # Insert 36 at the beginning
 list.push(36);
 # Insert 18 at the beginning. So linked list becomes 18->36->None
 list.push(18);
 # Insert 52 at the beginning. So linked list becomes 52->18->36->None
 list.push(52);
 list.push(2);
 list.push(73);
 print \'The list is:\',
 list.print_the_List()
 # Insert 22, after 52. The linked list will becomes 73->2->22->52->18->36->None None
 list.insert_After(list.head.next, 22)
 
 print \'\ The list after inserting 22 is:\',
 list.print_the_List()
![[Python] [Singly-linked list] [Element insertion] Consider the following singly linked list. Provide the instructions to insert the new node immediately followi [Python] [Singly-linked list] [Element insertion] Consider the following singly linked list. Provide the instructions to insert the new node immediately followi](/WebImages/31/python-singlylinked-list-element-insertion-consider-the-foll-1090360-1761574023-0.webp)
![[Python] [Singly-linked list] [Element insertion] Consider the following singly linked list. Provide the instructions to insert the new node immediately followi [Python] [Singly-linked list] [Element insertion] Consider the following singly linked list. Provide the instructions to insert the new node immediately followi](/WebImages/31/python-singlylinked-list-element-insertion-consider-the-foll-1090360-1761574023-1.webp)
