So I know about Floyd's cycle detection algorithm but while going over the problem I came up with another idea to solve it.
If we can store the 'nextpointer' of every node in a vector/list while we traverse the linked list and the count if the frequency of any element is more than 1 or not. If any value in the vector/list occurs more than once, it basically means that a single node has been pointed to twice(or more) and hence, it becomes a cycle.
I couldn't manage to code the same in Python 3. would really appreciate if y'all could help me out. Thanks.
class Node:
head = None
def __init__(self, data=None, nextnode=None):
self.data = data
self.next = nextnode
def findMergeNode(head1, head2):
a = set()
b = set()
while (head1 and head2):
a.add(head1)
head1 = head1.next
b.add(head2)
head2 = head2.next
if (a.intersection(b)):
return a.intersection(b)