# 判断两个链表是否相交
# 方法一,首尾相接法。先首尾相连,再判断是否有环。有环则说明相交
# 首尾相连
def create_annulation(pHead1, pHead2):
if not pHead1 or not pHead2 or not pHead1.next or not pHead2.next:
return None
last = pHead1.next # 指向pHead1最后一个节点
while last.next:
last = last.next
# p1最后节点的next指向p2头节点
last.next = pHead2
return pHead1
# 判断是否有环
def exist_loop(pHead):
if not pHead or not pHead.next:
return None
slow = pHead
fast = pHead
while slow.next and fast.next.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
# 方法二,HashSet法。遍历链表1,将所有next域的节点存储在hashset中,遍历链表2,与当前hashset中的值去比较,如果有相同的,则说明相交了。
def judge_x(pHead1, pHead2):
if not pHead1 or not pHead2 or not pHead1.next or not pHead2.next:
return None
hashset = set()
p = pHead1 # 用来遍历链表
hashset.add(p)
while p.next:
p = p.next
hashset.add(p)
# 这里注意要你把所有的节点都存储到hashset中
p = pHead2
while p:
if p.next in hashset:
return True
p = p.next
return False
if __name__ == "__main__":
# 先构造出两个相交的链表
pHead1 = LNode(0)
p1 = LNode(1)
p2 = LNode(2)
p3 = LNode(3)
p4 = LNode(4)
pHead1.next = p1
p1.next = p2
p2.next = p3
p3.next = p4
pHead2 = LNode(10)
pa = LNode(11)
pHead2.next = pa
pa.next = p2
p2.next = p3
p3.next = p4
# newPhead1 = create_annulation(pHead1, pHead2)
# print (exit_loop(newPhead1))
print (judge_x(pHead1, pHead2))
如何判断两个链表是否相交,python实现
最新推荐文章于 2023-04-10 20:18:56 发布