If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Sure! Here's the Python code to implement insertion in a sorted linked list:
pythonCopy code
class Node: def __init__(self, data): self.data = data self.next = None class SortedLinkedList: def __init__(self): self.head = None def insert(self, data): new_node = Node(data) if not self.head or data <= self.head.data: new_node.next = self.head self.head = new_node else: current = self.head while current.next and current.next.data < data: current = current.next new_node.next = current.next current.next = new_node def display(self): current = self.head while current: print(current.data, end=" -> ") current = current.next print("None") # Example usage: if __name__ == "__main__": sorted_linked_list = SortedLinkedList() # Insert elements to create the sorted linked list sorted_linked_list.insert(3) sorted_linked_list.insert(7) sorted_linked_list.insert(1) sorted_linked_list.insert(9) # Display the sorted linked list print("Sorted Linked List:") sorted_linked_list.display()In this code, we have implemented the
SortedLinkedListclass, which includes theNodeclass for representing nodes in the linked list. TheSortedLinkedListclass has aninsertmethod that inserts elements in a sorted order.We start by creating a new node with the data to be inserted. If the linked list is empty or the data is less than or equal to the head's data, we insert the new node at the beginning. Otherwise, we traverse the linked list to find the appropriate position for the new node while maintaining the sorted order.
In the example usage, we insert elements 3, 7, 1, and 9 into the sorted linked list and then display the final sorted linked list.
The output will be:
rustCopy code
Sorted Linked List: 1 -> 3 -> 7 -> 9 -> NoneThe linked list is created with elements inserted in sorted order, resulting in the sorted order 1 -> 3 -> 7 -> 9.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support