Skip to main content

Find length of circular linked list in python

Python program for Find length of circular linked list . Here problem description and other solutions.

#  Python 3 program for
#  Count number of nodes in circular linked list 

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

class CircularLinkedList :
	#  Class constructor
	def __init__(self) :
		self.head = None
	
	#  Insert node at end of circular linked list
	def insert(self, value) :
		#  Create a new node
		node = LinkNode(value, self.head)
		if (self.head == None) :
			#  First node of linked list
			self.head = node
			node.next = self.head
		else :
			temp = self.head
			#  Find the last node
			while (temp.next != self.head) :
				#  Visit to next node
				temp = temp.next
			
			#  Add new node at the last 
			temp.next = node
		
	
	def countNode(self) :
		if (self.head == None) :
			return 0
		
		#  Start with second node
		temp = self.head.next
		#  This is used to count linked node
		count = 1
		#  iterate circular linked list
		while (temp != self.head) :
			count += 1
			#  Visit to next node
			temp = temp.next
		
		return count
	

def main() :
	cll = CircularLinkedList()
	#  Add nodes
	cll.insert(1)
	cll.insert(3)
	cll.insert(5)
	cll.insert(7)
	cll.insert(9)
	cll.insert(11)
	#  Display result
	print(cll.countNode())

if __name__ == "__main__": main()

Output

6




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