Python:如何判断两个单链表(无环)是否交叉

class LNode:
    def __init__(self):
        self.data = None
        self.next = None

def IsIntersect(head1, head2):
    if head1 == None or head1.next == None or head2 == None or head2.next == None or head1 == head2:
        return None
    tmp1 = head1.next
    tmp2 = head2.next
    n1, n2 = 1, 1
    while tmp1.next != None:
        tmp1 = tmp1.next
        n1 += 1
    while tmp2.next != None:
        tmp2 = tmp2.next
        n2 += 1
    if tmp1 == tmp2:
        if n1 > n2 :
            while n1 - n2 > 0:
                head1 = head1.next
                n1 -= 1
        if n2 >n1 :
            while n2 - n1 >0:
                head2 = head2.next
                n2 -= 1
        while head1 != head2:
            head1 = head1.next
            head2 = head2.next
        return head1
    else:
        return None

if __name__ == '__main__':
    head1 = LNode()
    head2 = LNode()
    cur = head1
    i= 1
    while i<8 :
        tmp = LNode()
        tmp.data = i
        cur.next = tmp
        cur = tmp
        if i==5 :
            p = tmp
        i += 1
    cur = head2
    i= 1
    while i<5 :
        tmp = LNode()
        tmp.data = i
        cur.next = tmp
        cur = tmp
        i += 1
    cur.next = p
    interNode = IsIntersect(head1,head2)
    if interNode is not None:
        print('两个链表相交点为:'+str(interNode.data))
    else:
        print('不相交')

运行结果

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值