Sorted order insertion in doubly linked list in python

Python program for Sorted order insertion in doubly linked list. Here problem description and explanation.

#  Python 3 Program For
#  Insert node in sorted order 

#  Define class of linked list Node
class LinkNode :
	def __init__(self, data) :
		self.data = data
		self.next = None
		self.prev = None

class DoublyLinkedList :
	def __init__(self) :
		self.head = None
	
	#  Insert Node at sorted way
	def insert(self, value) :
		#  Create a dynamic node
		node = LinkNode(value)
		if (self.head == None) :
			#  Add first node
			self.head = node
		elif (self.head.data >= node.data) :
			#  When need to add node at begining position
			self.head.prev = node
			node.next = self.head
			self.head = node
		else :
			current = self.head
			#  Find position to add new node
			while (current != None and current.next != None and current.next.data <= value) :
				current = current.next
			
			#  Insert new node between the nodes
			node.next = current.next
			if (current.next != None) :
				#  When next node exists
				current.next.prev = node
			
			node.prev = current
			current.next = node
		
	
	#  Display node element of doubly linked list
	def display(self) :
		if (self.head == None) :
			print("Empty Linked List")
		else :
			print("Linked List Head to Tail :", end = "")
			#  Get first node of linked list
			temp = self.head
			last = None
			#  iterate linked list 
			while (temp != None) :
				#  Display node value
				print("  ", temp.data, end = "")
				last = temp
				#  Visit to next node
				temp = temp.next
			
			print("\nLinked List Tail to Head :", end = "")
			#  Get last node of linked list
			temp = last
			#  iterate linked list 
			while (temp != None) :
				#  Display node value
				print("  ", temp.data, end = "")
				#  Visit to prev node
				temp = temp.prev
			
		
	

def main() :
	dll = DoublyLinkedList()
	#  Insert following linked list nodes
	dll.insert(5)
	dll.insert(3)
	dll.insert(11)
	dll.insert(4)
	dll.insert(6)
	dll.insert(1)
	dll.insert(8)
	dll.insert(12)
	dll.display()

if __name__ == "__main__": main()
Sorted insertion in doubly linked list in python

Output

Linked List Head to Tail :   1   3   4   5   6   8   11   12
Linked List Tail to Head :   12   11   8   6   5   4   3   1



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







© 2022, kalkicode.com, All rights reserved