两个链表交集

 题目给定两个链表,两个链表有一部分是一样,求给出两个链表交集开始的地方。

方法1

步骤1 ,求先求出两个链表的长度差,然后让

步骤2,长度较长的链表,向后移动长度差。使得两个链表后续遍历长度相同,

步骤3 ,最后移动两个指针,一次对比数据,

def getIntersectionNode(headA,headB):
    curA,curB = headA,headB
    lenA,lenB = 0,0
    while curA is not None:
        lenA += 1
        curA = curA.next
    while curB is not None:
        lenB += 1
        curB = curB.next
    curA,curB = headA,headB
    if lenA > lenB:
        for i in range(lenA-lenB):
            curA = curA.next
    elif lenB > lenA:
        for i in range(lenB - lenA):
            curB = curB.next
    while curB != curA:
        curB = curB.next
        curA = curA.next
    return curA

 方法2 ,将两个链表相互补齐,然后遍历,

def getIntersectionNode2(headA,headB):
    if headA and headB:
        A,B = headA,headB
        while A != B:
            A = A.next if A else headB
            B = B.next if B else headA
        return A 
    
    

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值