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

    你可能感兴趣的文章
    php zookeeper实现分布式锁
    查看>>
    PHP 中 this,self,parent 的区别、用法
    查看>>
    PHP 中如何高效地处理大规模数据的排序?
    查看>>
    PHP 之ftp客户端类封装实现
    查看>>
    php 代码改进
    查看>>
    php 代码混淆
    查看>>
    PHP 使用 $_SERVER['PHP_SELF'] 获取当前页面地址及其安全性问题
    查看>>
    Redis系列之如何避免缓存击穿
    查看>>
    php 内存分析
    查看>>
    PHP 函数名前面加&
    查看>>
    redis报错
    查看>>
    php 删除包含某一字符的数组元素
    查看>>
    Redis学习总结(19)——Redis 5种集群方式对比
    查看>>
    php 反射
    查看>>
    php 处理 大并发
    查看>>
    php 大文件上传
    查看>>
    php 子进程监听消息,swoole学习笔记之多线程端口监听问题记录 多进程epoll模式...
    查看>>
    PHP 学习笔记 (四)
    查看>>
    Redis入门概述
    查看>>
    php 实现Iterator 接口
    查看>>