Skip to main content

Find middle element of circular linked list in python

Python program for Find middle element of circular linked list. Here problem description and explanation.

#  Python 3 Program 
#  Find middle element in circular linked list
class LinkNode :
	def __init__(self, data) :
		self.data = data
		self.next = None
	

class CircularLinkedList :
	#  Class constructor
	def __init__(self) :
		self.head = None
	
	#  Add element at end of circular linked list
	def insert(self, data) :
		#  Create a new node
		node = LinkNode(data)
		if (self.head == None) :
			self.head = node
		else :
			temp = self.head
			#  Find the last node
			while (temp.next != self.head) :
				#  Visit to next node
				temp = temp.next
			
			#  Add node
			temp.next = node
		
		#  Connect last node to head
		node.next = self.head
	
	#  Display node element of circular linked list
	def display(self) :
		if (self.head == None) :
			print("Empty Linked List")
		else :
			temp = self.head
			#  iterate linked list
			while (temp != None) :
				#  Display node
				print("", temp.data, end = " ")
				#  Visit to next node
				temp = temp.next
				if (temp == self.head) :
					#  Stop iteration
					return
				
			
		
	
	#  Find middle node of given circular linked list
	def findMiddle(self) :
		if (self.head == None) :
			print("Empty Linked List")
		else :
			if (self.head.next != self.head and 
                self.head.next.next != self.head) :
				temp = self.head
				middle = self.head
				#  Find middle node
				while (temp != None and 
                       temp.next != self.head and 
                       temp.next.next != self.head) :
					middle = middle.next
					temp = temp.next.next
				
				print("\n Middle Node is : ", middle.data)
			else :
				print("\nLess than three nodes")
			
		
	

def main() :
	cll = CircularLinkedList()
	#  Add linked list nodes
	cll.insert(1)
	cll.insert(2)
	cll.insert(3)
	cll.insert(4)
	cll.insert(5)
	cll.insert(6)
	cll.insert(7)
	cll.display()
	cll.findMiddle()

if __name__ == "__main__": main()

Output

 1  2  3  4  5  6  7
 Middle Node is :  4




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