美文网首页
【链表】两个链表的第一个公共结点

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

作者: 一个想当大佬的菜鸡 | 来源:发表于2019-08-26 16:00 被阅读0次
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        m = self.getLen(pHead1)
        n = self.getLen(pHead2)
        if m < n:
            pHead1, pHead2 = pHead2, pHead1
            m, n = n, m
        for i in range(m-n):
            pHead1 = pHead1.next
        while pHead1 and pHead2:
            if pHead1 == pHead2:
                return pHead1
            pHead1 = pHead1.next
            pHead2 = pHead2.next
    def getLen(self, p):
        m = 0
        while p:
            m += 1
            p = p.next
        return m

相关文章

网友评论

      本文标题:【链表】两个链表的第一个公共结点

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