Skip to main content

Insertion at end of circular doubly linked list in python

Python program for Insertion at end of circular doubly linked list. Here problem description and explanation.

#  Python 3 Program 
#  Insert node at end of circular doubly linked list

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

class CircularDLL :
	def __init__(self) :
		self.head = None
		self.tail = None
	
	#  Insert node at end of circular doubly linked list
	def insert(self, value) :
		#  Create a node
		node = LinkNode(value)
		if (self.head == None) :
			#  First node of linked list
			self.head = node
			self.tail = node
			node.next = node
			node.prev = node
		else :
			node.next = self.head
			node.prev = self.tail
			self.head.prev = node
			self.tail.next = node
			#  Set new last node
			self.tail = node
		
	
	def headToTail(self) :
		if (self.head == None) :
			print("Empty linked list")
		else :
			temp = self.head
			print("\nNode Form Front to Rear :")
			while (temp != None) :
				print("  ", temp.data, end = "")
				temp = temp.next
				if (temp == self.head) :
					return
				
			
		
	
	def tailToHead(self) :
		if (self.tail == None) :
			print("Empty linked list", end = "")
		else :
			temp = self.tail
			print("\nNode Form Rear to Front :")
			while (temp != None) :
				print("  ", temp.data, end = "")
				temp = temp.prev
				if (temp == self.tail) :
					return
				
			
		
	

def main() :
	cdll = CircularDLL()
	#  Add following linked list nodes
	cdll.insert(1)
	cdll.insert(2)
	cdll.insert(3)
	cdll.insert(4)
	cdll.insert(5)
	cdll.insert(6)
	#  Display node
	cdll.headToTail()
	cdll.tailToHead()

if __name__ == "__main__": main()

Output

Node Form Front to Rear :
   1   2   3   4   5   6
Node Form Rear to Front :
   6   5   4   3   2   1




Comment

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