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

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

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

from functools import total_ordering
from re import L
from operator import le
# 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
        pHead1_length = 0
        pHead2_length = 0
        p = pHead1
        q = pHead2
        while(p):
            pHead1_length = pHead1_length + 1
            p=p.next
        while(q):
            pHead2_length = pHead2_length + 1
            q = q.next
        p = pHead1
        q = pHead2
        if pHead1_length< pHead2_length:
            p = pHead2
            q = pHead1
        index = abs(pHead1_length - pHead2_length)
        while(index>0):
            p=p.next
            index = index -1 
        while(p and q):
            if (p == q):
                return p
            p = p.next
            q = q.next
        
        return None


                

        

全部评论
点赞 回复 分享
发布于 02-26 20:17 广东

相关推荐

06-20 17:42
东华大学 Java
凉风落木楚山秋:要是在2015,你这简历还可以月入十万,可惜现在是2025,已经跟不上版本了
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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