所以我知道弗洛伊德的循环检测算法,但是在研究这个问题时,我想出了另一个解决它的想法。
如果我们可以在遍历链表时将每个节点的“ nextpointer ”存储在向量/列表中,如果任何元素的频率大于1,则计数。如果向量/列表中的任何值出现不止一次,则基本上意味着单个节点已被指向两次(或更多),因此它变成了一个循环。
我无法在 Python 3 中编写相同的代码。如果你们能帮助我,我将不胜感激。谢谢。
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)