程序员面试算法宝典-1.11 如何判断两个单链表(无环)是否交叉

# 声明结点
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
    temp1 = head1.next
    temp2 = head2.next
    n1, n2 = 0, 0
    # 遍历head1,找到尾结点
    while temp1.next!=None:
        n1 += 1
        temp1 = temp1.next
    # 遍历head2,找到尾结点
    while temp2.next!=None:
        n2 += 1
        temp2 = temp2.next
    if temp1.data!=temp2.data:
        return None
    else:
        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

if __name__=="__main__":
    head1 = LNode()
    head2 = LNode()
    cur = head1
    i = 1
    # 构造第一个链表
    while i<8:
        temp = LNode()
        temp.data = i
        cur.next = temp
        cur = temp
        if i==5:
            p=temp
        i += 1
    # 构造第二个链表
    cur = head2
    i = 1
    while i<5:
        temp = LNode()
        temp.data = i
        cur.next = temp
        cur = temp
        i += 1
    # 使他们相交于点5
    cur.next = p
    interNode = IsIntersect(head1, head2)
    if interNode == None:
        print("这两个链表不相交")
    else:
        print("这两个链表相交点为:"+str(interNode.data))

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值