剑指offer 两个链表的第一个公共结点 python

版权声明:本文为博主原创文章,需转载可以私信我,同意后即可 https://blog.csdn.net/Sun_White_Boy/article/details/83065219

题目描述

输入两个链表,找出它们的第一个公共结点。

样例


想法一:
遍历第一个链表,将所有元素添加到列表当中,遍历第二个链表,拿节点查找是否存在于列表中,如果找到了公共节点,则返回该节点,如果无,返回None

class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        list1 = []
        while pHead1:
            list1.append(pHead1.val)
            pHead1 = pHead1.next
        while pHead2:
            if pHead2.val in list1:
                return pHead2
            pHead2 = pHead2.next
        return None

想法二:
如果两个链表长度一样,则正常遍历,找到相同的或者不存在。
如果两个链表长度不同,则首先短的遍历结束后会从另一个链表开头开始遍历,而当另一个节点遍历结束后从另一个链表头开始遍历时,这两个链表的差则会消除。
解释图

class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        p1 = pHead1
        p2 = pHead2
        while p1 != p2:
            p1 = pHead2 if p1 is None else p1.next
            p2 = pHead1 if p2 is None else p2.next
        return p1

最后

刷过的LeetCode或剑指offer源码放在Github上了,希望喜欢或者觉得有用的朋友点个star或者follow。
有任何问题可以在下面评论或者通过私信或联系方式找我。
联系方式
QQ:791034063
Wechat:liuyuhang791034063
CSDN:https://blog.csdn.net/Sun_White_Boy
Github:https://github.com/liuyuhang791034063

猜你喜欢

转载自blog.csdn.net/Sun_White_Boy/article/details/83065219
今日推荐