如何判断两个链表是否相交,python实现

# 判断两个链表是否相交
# 方法一,首尾相接法。先首尾相连,再判断是否有环。有环则说明相交
# 首尾相连
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))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值