Sorted insertion in circular linked list in python
Python program for Sorted insertion in circular linked list. Here more information.
# Python 3 program for
# Sorted insert for circular linked list
class LinkNode :
def __init__(self, data) :
self.data = data
self.next = None
class CircularLinkedList :
def __init__(self) :
self.head = None
self.tail = None
def insert(self, value) :
node = LinkNode(value)
if (self.head == None) :
# First node of linked list
self.head = node
self.tail = node
node.next = node
elif (self.head.data >= value) :
# Add node at beginning of linked list
node.next = self.head
self.head = node
self.tail.next = node
elif (self.tail.data <= value) :
# Add node at last position
self.tail.next = node
self.tail = node
node.next = self.head
else :
# When adding a new node at intermediate position
temp = self.head
# Find valid sorted position to add new node
while (temp != None and temp.next.data < value) :
# Visit to next node
temp = temp.next
# Add new node
node.next = temp.next
temp.next = node
# Display node element of circular linked list
def display(self) :
if (self.head == None) :
print(" Empty Linked List")
else :
print(" Circular Linked List Element ")
# First node of linked list
print(" ", self.head.data, end = "")
temp = self.head.next
# Display linked list node
while (temp != None and temp != self.head) :
# Display node value
print(" ", temp.data, end = "")
# Visit to next node
temp = temp.next
def main() :
cll = CircularLinkedList()
# Add linked list node
cll.insert(8)
cll.insert(17)
cll.insert(26)
cll.insert(25)
cll.insert(14)
cll.insert(5)
cll.insert(-3)
cll.insert(62)
cll.insert(5)
cll.insert(34)
# Display node value
cll.display()
if __name__ == "__main__": main()

Output
Circular Linked List Element
-3 5 5 8 14 17 25 26 34 62
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment