insert method for a sorted doubly linked list in python

To insert a new node in a sorted doubly linked list, we need to traverse the list until we find a node with a larger value than the value of the new node to be inserted. Once we find that node, we insert the new node before it.

Here's an implementation of the insert method for a sorted doubly linked list in Python:

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

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

    def insert(self, data):
        new_node = Node(data)

        # If the list is empty, make the new node the head
        if self.head is None:
            self.head = new_node
            return

        # If the new node is smaller than the head, insert it before the head
        if self.head.data > data:
            new_node.next = self.head
            self.head.prev = new_node
            self.head = new_node
            return

        # Traverse the list to find the node with a larger value than the new node
        curr_node = self.head
        while curr_node.next is not None and curr_node.next.data < data:
            curr_node = curr_node.next

        # Insert the new node before the node with a larger value
        new_node.next = curr_node.next
        if curr_node.next is not None:
            curr_node.next.prev = new_node
        curr_node.next = new_node
        new_node.prev = curr_node
        
1135 chars
38 lines

In this method, we first create a new node with the given data. If the list is empty, we make the new node the head and return. Otherwise, we check if the new node is smaller than the head. If it is, we insert it before the head and return.

If the new node is not smaller than the head, we traverse the list until we find a node whose data is larger than the new node. We then insert the new node before that node.

Note that this method assumes that the list is already sorted in ascending order. If the list is not sorted, the method will insert the new node at the correct position assuming that the remaining nodes are also in ascending order.

gistlibby LogSnag