Question:
How to insert a new node in a sorted circular linked list using Python3

Summary

Here, we have defined a method as ‘sortedInsert’ to insert a new node with a given data value into a sorted circular linked list.  


Solution

#User function Template for python3


'''

class Node: 

    # Constructor to initialize the node object 

    def __init__(self, data): 

        self.data = data 

        self.next = None

  '''

class Solution:

    def sortedInsert(self, head, data):

        new_node = Node(data)


        # Case: Empty linked list

        if not head:

            new_node.next = new_node

            return new_node


        current = head


        # Case: Insert at the beginning

        if data < head.data:

            while current.next != head:

                current = current.next

            current.next = new_node

            new_node.next = head

            return new_node


        # Case: Insert in the middle or at the end

        while current.next != head and current.next.data < data:

            current = current.next


        new_node.next = current.next

        current.next = new_node


        return head


Explanation

  • The parameters for the sortedInsert method are a data value (data) and the head of a sorted circular linked list (head).

  • With the supplied data value, a new node (new_node) is created.

  • Empty Linked List: The new node is returned and the next node is set to itself if the linked list is empty.


Suggested blogs:

>How to sort the array in ascending order using Python?

>How to keep the focus on the secondary row even after deleting that row in Python?

>How to use if/else in Python to change to a different audio channel?

>How to clone a repo into local repo and install the pip package via the local repo?

>How to fix Uncaught ReferenceError in python?

>How to Install mariaDB client efficiently inside docker?

>Steps to setup typing annotations on my script: Python

>Why nn.Dropout change the elements values of a tensor in Python?

>How to generate code with Source Generator in c# into class library project?

>How to make parabolic frame movement independent in Python?

>How to make tkinter whiteboard transparent?

>How is link class Franchise with Class Menu in Python Code?


Nisha Patel

Nisha Patel

Submit
0 Answers