Task 1:
Here is the implementation of insert and delete methods for the LinkedList class:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
curr_node = self.head
while curr_node.next is not None:
curr_node = curr_node.next
curr_node.next = new_node
def delete(self, data):
if self.head is None:
return
if self.head.data == data:
temp = self.head
self.head = temp.next
temp = None
return
prev_node = None
curr_node = self.head
while curr_node is not None and curr_node.data != data:
prev_node = curr_node
curr_node = curr_node.next
if curr_node is not None:
prev_node.next = curr_node.next
Task 2:
Here is the implementation of insertion sort algorithm for sorting linked lists along with printing the order of elements in the linked list after each insertion:
def insert_sort_linkedlist(a):
if a is None or a.next is None:
return a
sorted_list_head = a # head of sorted list which starts with first element of unsorted list
unsorted_list_head=a.next # head of unsorted list which starts from second element
sorted_list_head.next=None # setting next pointer to none as we are building list again
while unsorted_list_head!=None:
current=unsorted_list_head #taking first element from unsorted list
unsorted_list_head=unsorted_list_head.next #moving head to next node
#If current element is smaller than first element of sorted list
if current.data < sorted_list_head.data:
current.next=sorted_list_head
sorted_list_head=current
else:
#searching for the right position where we can insert this node
temp=sorted_list_head
while(temp!=None):
if (temp.next==None or current.data<temp.next.data):
current.next=temp.next
temp.next=current
break
temp=temp.next
#printing order of elements in linked list after each insertion
print("Order of elements: ", end='')
temp = sorted_list_head
while(temp!=None):
print(temp.data, end=' ')
temp=temp.next
print()
return sorted_list_head
#testing with sample input llist = LinkedList() llist.insert(5) llist.insert(2) llist.insert(4) llist.insert(1) print(“Before Sorting”) temp = llist.head while(temp!=None):
print(temp.data, end=' ')
temp=temp.next
print(“\nAfter Sorting”) insert_sort_linkedlist(llist.head)




