TRAINLOOP Editorial

Problem Explanation

Given a linked list, We have to tell if it is a circular linked list or not.

Approach

We can take a make to track the visited nodes, and if the revisit a visited node we can check if it is the head or not. If the revisited node is the head, then the linked list is circular else it is just a linked list with a cycle in between.

class ListNode:
def init(self,value):
self.value=value
self.next=None

def circular(head):
if not head:
return False
visited=set()
current=head
while current:
if current in visited:
return current==head
visited.add(current)
current=current.next
return False

head=ListNode(10)
node2=ListNode(21)
node3=ListNode(32)
node4=ListNode(42)
head.next=node2
node2.next=node3
node3.next=node4
node4.next=head
print(circular(head))

head=ListNode(11)
node2=ListNode(22)
node3=ListNode(33)
head.next=node2
node2.next=node3
print(circular(head))

1 Like