博客
关于我
【leetcode】相交链表
阅读量:541 次
发布时间:2019-03-09

本文共 1197 字,大约阅读时间需要 3 分钟。

为了解决这个问题,我们需要找到两个单链表的交点。交点是两个链表中的相同节点,并且不能返回0这个节点。

方法思路

为了找到两个链表的交点,我们可以利用以下方法:

  • 计算链表长度:首先计算两个链表的长度,确定较长链表和较短链表。
  • 移动指针:让较长链表的指针先移动较短链表的长度,这样两个指针会在交点后同时移动。
  • 同时移动指针:从交点后继续同时移动两个指针,直到找到交点或其中一个指针到达末尾。
  • 这种方法确保了我们在O(n)时间复杂度和O(1)空间复杂度内找到交点。

    解决代码

    class ListNode:    def __init__(self, val):        self.val = val        self.next = Nonedef getLen(node):    if node is None:        return 0    res = 0    while node is not None:        res += 1        node = node.next    return resdef getIntersectionNode(headA, headB):    lenA = getLen(headA)    lenB = getLen(headB)        # 计算长度差    len_diff = abs(lenA - lenB)        # 使较长的链表走到差的位置    if lenA > lenB:        currentA = headA        for _ in range(len_diff):            currentA = currentA.next    else:        currentB = headB        for _ in range(len_diff):            currentB = currentB.next        # 同时移动两个指针    while currentA is not None and currentB is not None:        if currentA == currentB:            return currentA        currentA = currentA.next        currentB = currentB.next        return None

    代码解释

  • ListNode类:定义了链表的节点,包含值和指向下一个节点的属性。
  • getLen函数:计算链表的长度,返回节点数。
  • getIntersectionNode函数:
    • 计算两个链表的长度。
    • 确定较长链表并让其指针移动到较短链表的长度处。
    • 同时移动两个指针,找到交点或返回null。
  • 转载地址:http://zthiz.baihongyu.com/

    你可能感兴趣的文章
    Python变量命名方法-ChatGPT4o作答
    查看>>
    Python变量与运算符
    查看>>
    Python变量/运算符/函数/模块/string
    查看>>
    python发送邮件的时候出现 error (535, b‘5.7.3 Authentication unsuccessful‘) 解决方法
    查看>>
    python系列【仅供参考】:python flask框架 debug功能
    查看>>
    python发送notes邮件_使用python在Lotus Notes中发送邮件
    查看>>
    Python双版本下创建一个Scrapy(西瓜皮)项目
    查看>>
    Python双版本下No module named 'requests'
    查看>>
    python及pycharm2018软件安装教程
    查看>>
    python去重txt文本_Python实现的txt文件去重功能示例
    查看>>
    python去掉列表的逗号,从Python列表项中删除标点符号
    查看>>
    Python卸载所有包
    查看>>
    python单线程下实现多个socket并发
    查看>>
    Python单元测试框架介绍(超详细~)
    查看>>
    Python单元测试框架
    查看>>
    python单元测试之unittest
    查看>>
    Python单元测试unittest实战
    查看>>
    Python单元测试-模拟VS补丁
    查看>>
    python协程实时输出_Python 协程以及事件循环的问题,怎么知道 IO 读取结束了呢?...
    查看>>
    Python十进制&;包提供错误的结果
    查看>>