美文网首页
两个链表的第一个公共节点

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

作者: 而立之年的技术控 | 来源:发表于2019-12-22 17:58 被阅读0次
    微信图片_20191222175705.jpg
    class Solution:
        def FindFirstCommonNode(self, pHead1, pHead2):
            # write code here
            if pHead1 is None or pHead2 is None:
                return None
            tmp1 = pHead1
            tmp2 = pHead2
            
            len1 = 0
            len2 = 0
            while tmp1:
                len1 += 1
                tmp1 = tmp1.next
            while tmp2:
                len2 += 1
                tmp2 = tmp2.next
            if len1 > len2:
                k = len1 - len2
                for i in range(k):
                    pHead1 = pHead1.next
                while pHead1 != pHead2:
                    pHead1 = pHead1.next
                    pHead2 = pHead2.next
                return pHead1
            else:
                k = len2 - len1
                for i in range(k):
                    pHead2 = pHead2.next
                while pHead1 != pHead2:
                    pHead1 = pHead1.next
                    pHead2 = pHead2.next
                return pHead1
    

    相关文章

      网友评论

          本文标题:两个链表的第一个公共节点

          本文链接:https://www.haomeiwen.com/subject/vzwonctx.html