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

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

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
        z1=pHead1
        z2=pHead2
        z1toz2=False
        z2toz1=False
        if z1 is None:
            return None
        if z2 is None:
            return None
        while z1 != z2:
            if z1 is None and z2 is None and z1toz2 and z2toz1:
                return None
            if z1.next is None and   z1toz2==False:
                # z1.next = pHead2
                # temp = z1
                z1 = pHead2
                # temp.next = None
                z1toz2 =  True
            else:
                z1=z1.next

            if z2.next is None and z2toz1==False:
                # z2.next = pHead1
                # temp = z2
                z2 = pHead1
                # temp.next = None
                z2toz1 = True
            else:
                z2=z2.next
            
            
        return z1

假如链路A是由a+c组成,B由b+c组成,A+B=a+c+b+c;B+A=b+c+a+c,所以同时遍历AB链路可以同时到达第一个公共节点。

全部评论

相关推荐

一表renzha:手写数字识别就是一个作业而已
点赞 评论 收藏
分享
想按时下班的大菠萝在...:隔壁学校的,加油多投, 实在不好找可以下个学期开学找,把算法八股准备好,项目有空再换换
投了多少份简历才上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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