def is_circular_linked_list(self, input_list):
if input_list.head:
cur = input_list.head
while cur.next:
cur = cur.next
if cur.next == input_list.head:
return True
return False
else:
return False
Let’s discuss the class method is_circular_linked_list. First, we check whether or not parameter is empty. If yes, we simply return False. Otherwise, we proceed as follows:
On line 3, we initialize cur to input_list.head so that we are able to traverse input_list that has been passed to is_circular_linked_list. On line 4 we set up a while loop which runs until cur.next becomes None. If cur.next becomes None, it implies that input_list must not be a circular linked list and therefore, if the while loop terminates, we return False on line 8. On the other hand, we update cur to cur.next in the while loop on line 5, and if we reach a node while traversing such that the next node is the head node, then this confirms that input_list is indeed a circular_linked_list. Hence, if the condition on line 6 turns out to be True, we return True from the method on line 7.
As you can see, the is_circular_linked_list method was pretty straightforward. Below we test it on a singly linked list and on a circular linked list: