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

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

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

from re import I
# class ListNode:
 
#from pandas import notnull
#     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
        i=pHead1
        j=pHead2
		#画图,可以得出如果不相交,i指针从链表1移动完,再从链表2移动完,正好,链表2从链表2移动完,然后从链表1移动完然后俩个指针都指向None
		#如果相交那么从i指针从链表1移动完,再移动到相交部分的,走过的节点数刚好等于j指针从链表2移动完,然后移动到相交的节点。
        while i!=j:
            if  i:
                i=i.next
            else:
                i=pHead2

            if j:
                j=j.next
            else:
                j=pHead1
        return i

全部评论

相关推荐

06-05 19:46
已编辑
武汉大学 后端
点赞 评论 收藏
分享
06-07 19:59
门头沟学院 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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