题解 | #两个链表的第一个公共结点#

两个链表的第一个公共结点

https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

#
# 
# @param pHead1 ListNode类 
# @param pHead2 ListNode类 
# @return ListNode类
#
class Solution:
    def FindFirstCommonNode(self , pHead1 , pHead2 ):
        # write code here
        if pHead1 is None or pHead2 is None:
            return None

        len1, len2 = 0, 0
        p1, p2 = pHead1, pHead2
        while p1 is not None:
            p1 = p1.next
            len1 = len1 + 1

        while p2 is not None:
            p2 = p2.next
            len2 = len2 + 1

        dif = 0
        while (len1 + dif) < len2:
            h1 = ListNode(0)
            h1.next = pHead1
            pHead1 = h1
            dif = dif + 1

        dif = 0
        while (len2 + dif) < len1:
            h2 = ListNode(0)
            h2.next = pHead2
            pHead2 = h2
            dif = dif + 1

        while pHead1 is not None and pHead2 is not None:
            if pHead1 == pHead2:
                break
            pHead1 = pHead1.next
            pHead2 = pHead2.next

        return pHead1

全部评论

相关推荐

沉淀一会:1.同学你面试评价不错,概率很大,请耐心等待; 2.你的排名比较靠前,不要担心,耐心等待; 3.问题不大,正在审批,不要着急签其他公司,等等我们! 4.预计9月中下旬,安心过节; 5.下周会有结果,请耐心等待下; 6.可能国庆节前后,一有结果我马上通知你; 7.预计10月中旬,再坚持一下; 8.正在走流程,就这两天了; 9.同学,结果我也不知道,你如果查到了也告诉我一声; 10.同学你出线不明朗,建议签其他公司保底! 11.同学你找了哪些公司,我也在找工作。
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务