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

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

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

#     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
        p1 = pHead1
        p2 = pHead2
        while pHead1 != pHead2:  # 为什么不用.val 是因为有可能为空的情况,没有.val属性
            if pHead1:
                pHead1 = pHead1.next
            else:
                 pHead1 = p2
            if pHead2:
                pHead2 = pHead2.next
            else:
                pHead2 = p1
        
        return pHead1
            
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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