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

  • Hash法
  • 首尾相接法:如把链表1 的尾结点接到链表2的头指针,然后判断链表2是否有环,参考如何判断一个单链表是否有环
  • 尾结点法
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('不相交')

运行结果

你可能感兴趣的:(编程练习1,Python)