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

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

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 ):
        if not pHead1 or not pHead2:
            return None
        len_1 = 0
        len_2 = 0
        head_1 = pHead1
        head_2 = pHead2
        #求链表长度
        while head_1:
            len_1 += 1
            head_1 = head_1.next
        while head_2:
            len_2 += 1
            head_2 = head_2.next
        #先走长出来的节点
        while len_1 > len_2:
            pHead1 = pHead1.next
            len_1 -= 1
        while len_1 < len_2:
            pHead2 = pHead2.next
            len_2 -= 1
        #两个链表同时往后走,直到相交。
        while pHead1 != pHead2:
            pHead1 = pHead1.next
            pHead2 = pHead2.next
        return pHead1
        
     
#     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 ):
        if not pHead1 or not pHead2:
            return None
        cur1 = pHead1
        cur2 = pHead2
        #路径1走链表1再走链表2;路径2走链表2再走链表1;如果两个路径相交,求出公共节点
        while cur1 != cur2:
            cur1 = cur1.next if cur1 else pHead2
            cur2 = cur2.next if cur2 else pHead1
  
        return cur1
        
全部评论

相关推荐

贺兰星辰:不要漏个人信息,除了简历模板不太好以外你这个个人简介是不是太夸大了...
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务