insert method for a sorted linked list in python

If we want to insert an element into a sorted linked list such that the list remains sorted, we need to traverse the list until we find the correct position for the new element. Once we find the correct position, we can insert the new element into the list.

Here's an implementation of the insert_sorted method for a singly linked list in Python:

main.py
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def insert_sorted(self, data):
        new_node = Node(data)
        # If the list is empty, new node becomes head
        if self.head is None:
            self.head = new_node
        else:
            # Traverse the list to find the correct position for the new node
            curr_node = self.head
            prev_node = None
            while curr_node is not None and curr_node.data < data:
                prev_node = curr_node
                curr_node = curr_node.next
            # Insert the new node at the correct position
            if prev_node is None:
                # The new node is the new head
                new_node.next = self.head
                self.head = new_node
            else:
                prev_node.next = new_node
                new_node.next = curr_node

    def print_list(self):
        curr_node = self.head
        while curr_node is not None:
            print(curr_node.data, end=" -> ")
            curr_node = curr_node.next
        print("None")
1167 chars
37 lines

Here's an example usage:

main.py
ll = LinkedList()
ll.insert_sorted(3) # List: 3 -> None
ll.insert_sorted(1) # List: 1 -> 3 -> None
ll.insert_sorted(5) # List: 1 -> 3 -> 5 -> None
ll.insert_sorted(4) # List: 1 -> 3 -> 4 -> 5 -> None
ll.print_list()     # Output: 1 -> 3 -> 4 -> 5 -> None
255 chars
7 lines

gistlibby LogSnag