博客
关于我
【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 valueerror object2_python遇到错误记录
    查看>>
    python vars的作用
    查看>>
    Python virtualenv
    查看>>
    python vue3实现大文件分段续传(断点续传)--带暂停和继续功能
    查看>>
    Python WebDriver如何打印整个页面源(html)
    查看>>
    Python WebSocket自动化测试:构建高效接口测试框架
    查看>>
    Python Web开发
    查看>>
    Redis 配置文件杂项。
    查看>>
    Python web自动化测试 —— 文件上传
    查看>>
    Python web自动化测试 —— 文件上传!
    查看>>
    Python Web自动化测试开发环境搭建(附安装包与虚拟机环境)
    查看>>
    python win32api键盘_Python win32api.keybd_event模拟键盘输入
    查看>>
    python Windows显示当前鼠标坐标
    查看>>
    python Workbook 表格宽度
    查看>>
    python | ggplot,一个超强的 Python 库!
    查看>>
    python | unoconv,一个超厉害的 Python 库!
    查看>>
    python | webassets,一个超强的 Python 库!
    查看>>
    python | werkzeug,一个不可思议的 Python 库!
    查看>>
    python | xlsxwriter,一个实用的 Python 库!
    查看>>
    python | xlwings,一个非常实用的 Excel 相关的 Python 库!
    查看>>