Posted on by Kalkicode
Code Circular Linked List

Check linked list is circular or not in python

Python program for Check linked list is circular or not . Here problem description and explanation.

#  Python 3 Program for
#  Check linked list is circular or not

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

class LinkedList :
	#  Class constructor
	def __init__(self) :
		self.head = None
	
	#  Check circular linked list or not
	#  Note that this function is not capable to detect loop
	def isCircular(self) :
		if (self.head == None) :
			#  Case when linked list is empty
			return False
		else :
			temp = self.head
			while (temp != None) :
				#  Visit to next node
				temp = temp.next
				if (temp == self.head) :
					#  When detecting circular node
					return True
				
			
			#  When not circular linked list
			return False
		
	

def main() :
	ll = LinkedList()
	#  insert element of linked list
	ll.head = LinkNode(1)
	ll.head.next = LinkNode(2)
	ll.head.next.next = LinkNode(3)
	ll.head.next.next.next = LinkNode(4)
	ll.head.next.next.next.next = LinkNode(5)
	if (ll.isCircular()) :
		print("Yes")
	else :
		print("No")
	
	#  Connect last node to head
	ll.head.next.next.next.next.next = ll.head
	if (ll.isCircular()) :
		print("Yes")
	else :
		print("No")
	

if __name__ == "__main__": main()

Output

No
Yes

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