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

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

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

全部评论

相关推荐

风中翠竹:真的真的真的没有kpi。。。面试官是没有任何kpi的,捞是真的想试试看这个行不行,碰碰运气,或者是面试官比较闲现在,没事捞个人看看。kpi算HR那边,但是只有你入职了,kpi才作数,面试是没有的。
双非有机会进大厂吗
点赞 评论 收藏
分享
重生我想学测开:嵌入式的问题,我准备入行京东外卖了
点赞 评论 收藏
分享
07-02 13:52
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务