博客
关于我
【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/

    你可能感兴趣的文章
    POI:POI+JXL实现xls文件添加水印
    查看>>
    POI:POI实现docx文件添加水印
    查看>>
    POJ 1006
    查看>>
    Quartz中时间表达式的设置-----corn表达式
    查看>>
    poj 1035
    查看>>
    POJ 1061 青蛙的约会 (扩展欧几里得)
    查看>>
    Quartz2.2.1简单使用
    查看>>
    POJ 1080 Human Gene Functions(DP:LCS)
    查看>>
    Quant 开源项目教程
    查看>>
    POJ 1088 滑雪
    查看>>
    POJ 1095 Trees Made to Order
    查看>>
    POJ 1113 Wall(计算几何--凸包的周长)
    查看>>
    poj 1125Stockbroker Grapevine(最短路)
    查看>>
    Qualitor processVariavel.php 未授权命令注入漏洞复现(CVE-2023-47253)
    查看>>
    poj 1151 (未完成) 扫描线 线段树 离散化
    查看>>
    POJ 1151 / HDU 1542 Atlantis 线段树求矩形面积并
    查看>>
    poj 1163 数塔
    查看>>
    POJ 1177 Picture(线段树:扫描线求轮廓周长)
    查看>>
    Qualitor checkAcesso.php 任意文件上传漏洞复现(CVE-2024-44849)
    查看>>
    POJ 1182 食物链(并查集拆点)
    查看>>