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

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

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 not pHead1 or not pHead2:
            return None
        p1,p2 = pHead1,pHead2
        while p1 != p2:
            if p1: p1 = p1.next    #双指针遍历完自己,遍历对方
            else: p1 = pHead2
            if p2: p2 = p2.next
            else: p2 = pHead1
        return p1                  #在公共节点或结尾None(无交集)相遇
        
全部评论

相关推荐

头像
04-09 14:29
Java
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务