【Leetcode】160. Intersection of Two Linked Lists

本文介绍了三种算法,用于解决寻找两个单链表的第一个公共节点的问题。通过一次或两次遍历链表,这些方法有效地确定了是否存在交点及其位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
在这里插入图片描述

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution1(object):
    """
    two pass method
    in first pass get each list's length la,lb, we assume that la > lb
    the longer link list take la - lb steps first , the they set out at the same time and will meet at the same time(if have)
    """
    def getIntersectionNode(self,headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        countA,countB,pNodeA,pNodeB = 0,0,headA,headB
        while(pNodeA):
            countA += 1
            pNodeA = pNodeA.next
        while(pNodeB):
            countB += 1
            pNodeB = pNodeB.next

        if countA < countB:
            headA, headB = headB, headA
            countA, countB = countB, countA
        while(countA != countB):
            countA -=1
            headA = headA.next
        while(headA and headB and headA!=headB):
            headA = headA.next
            headB = headB.next
        return headA

class Solution2(object):
    """
    Solution1 without count but pointer
    """
    def getIntersectionNode(self,headA, headB):
        l1,l2 = headA, headB
        while(l1 and l2):
            l1,l2 = l1.next, l2.next
        if l1 is None:
            l1,l2 = l2,l1
            headA,headB = headB, headA
        while(l1):
            headA = headA.next
            l1 = l1.next
        while(headA and headB and headA != headB):
            headA = headA.next
            headB = headB.next
        return headA if headA is None else headA.val



class Solution3(object):
    """
    If there exits an intersection between headA and headB ,
    If two people start from headA and headB  and change to the other list if they arrive in then end,
    they will meet at the intersection node (because they had walk the same distance)
    if the don't have intersection , after walk through two linklist, they have experience the same distance and come be none(None == None)
    """
    def getIntersectionNode(self,headA, headB):
        l1,l2 = headA, headB
        while(l1 != l2 ):
            l1  = l1.next if l1 != None else headB
            l2  = l2.next if l2 != None else headA
        return l1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值