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

题目要求:
思路:

思路1:常规遍历对比

思路2:转列表处理

思路3:双指针遍历(先走自己再走对方)

代码如下:

思路1代码:

python 复制代码
# class ListNode:
#     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
        index2 = pHead2
        while pHead1: # 依次遍历链表1
            pHead2 = index2 # 遍历链表2之前需要将其重新指向头
            while pHead2:
                if pHead1 == pHead2: # 比对成功后直接返回即可
                    return pHead1
                pHead2 = pHead2.next
            pHead1 = pHead1.next
        return None
        # write code here

思路2代码:

python 复制代码
# class ListNode:
#     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
        lists = [] # 将两张链表数据转成列表
        while pHead1:
            lists.append(pHead1)
            pHead1 = pHead1.next
        while pHead2:
            lists.append(pHead2)
            pHead2 = pHead2.next
        if len(lists) == len(set(lists)): # 如果去重后大小一致则不存在共同节点
            return None
        else: # 不一致的话遍历找到
            for item in lists:
                if lists.count(item) ==2:
                    return item
        # write code here

思路3代码:

python 复制代码
# class ListNode:
#     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):
        p1 = pHead1
        p2 = pHead2
        while p1 != p2: # 当相等时退出循环,此时p1=p2=None或p1=p2=共同节点
            p1 = p1.next if p1 else pHead2 # p1存在的情况下,将 p1.next属性赋值给p1否则将pHead2赋值给p1
            p2 = p2.next if p2 else pHead1
        return p1
        # write code here
相关推荐
CodeCraft Studio1 小时前
CAD文件处理控件Aspose.CAD教程:使用 Python 将绘图转换为 Photoshop
python·photoshop·cad·aspose·aspose.cad
Python×CATIA工业智造3 小时前
Frida RPC高级应用:动态模拟执行Android so文件实战指南
开发语言·python·pycharm
onceco3 小时前
领域LLM九讲——第5讲 为什么选择OpenManus而不是QwenAgent(附LLM免费api邀请码)
人工智能·python·深度学习·语言模型·自然语言处理·自动化
我叫小白菜4 小时前
【Java_EE】单例模式、阻塞队列、线程池、定时器
java·开发语言
狐凄4 小时前
Python实例题:基于 Python 的简单聊天机器人
开发语言·python
weixin_446122465 小时前
JAVA内存区域划分
java·开发语言·redis
悦悦子a啊5 小时前
Python之--基本知识
开发语言·前端·python
QuantumStack6 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
whoarethenext6 小时前
使用 C++/OpenCV 和 MFCC 构建双重认证智能门禁系统
开发语言·c++·opencv·mfcc
笑稀了的野生俊7 小时前
在服务器中下载 HuggingFace 模型:终极指南
linux·服务器·python·bash·gpu算力