博客
关于我
【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 中的机器学习简介:多项式回归
    查看>>
    python读取grib2数据_用Python加载grib2文件
    查看>>
    Python 中的注意点_s2
    查看>>
    Python读取Excel的几种工具包(附Demo)
    查看>>
    Python 中的生成器是什么?
    查看>>
    Python 中的离线语音转文本
    查看>>
    Python读写json文件的简单实现
    查看>>
    Python 中的线程
    查看>>
    Python 中的继承机制是什么样的?
    查看>>
    python读写excel之xlrd&xlwt&xlutils组合
    查看>>
    Python 中的装饰器是什么?
    查看>>
    Python 中的装饰器是如何工作的,有哪些实际应用场景?
    查看>>
    python读excel
    查看>>
    Python 中读取 CSV 文件-ChatGPT4o作答
    查看>>
    Python 之 filecmp
    查看>>
    python请求html_使用Python请求获取HTML?
    查看>>
    Python 之匿名函数和偏函数
    查看>>
    python 之栈的实现
    查看>>
    python语音播放
    查看>>
    python语言:装饰器原理
    查看>>