【Leetcode】【数据结构】【C语言】判断两个链表是否相交并返回交点地址

c 复制代码
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    struct ListNode *tailA=headA;
    struct ListNode *tailB=headB;
    int count1=0;
    int count2=0;
    //分别找尾节点,并顺便统计节点数量:
    while(tailA)
    {
        tailA=tailA->next;
        count1++;
    }
    while(tailB)
    {
        tailB=tailB->next;
        count2++;
    }
    if(tailA!=tailB)//如果尾节点不相同,则一定不相交
    return NULL;
    int tmp=abs(count1-count2);//得到两个数量差值的绝对值
    struct ListNode*longList=headA;
     struct ListNode*shortList=headB;
     //找出长的链表:
     if(count2>count1)
     {
         longList=headB;
         shortList=headA;
     }
     //先让长的链表走差值步,再和短链表齐头并进
     while(tmp)
     {
         longList=longList->next;
         tmp--;
     }
     //两个链表齐头并进:
     while(longList!=shortList)
     {
         shortList=shortList->next;
         longList=longList->next;
     }
     //两个链表相遇的地方就是节点
     return longList;
}
相关推荐
万法若空18 小时前
对数恒等式
人工智能·算法·机器学习
青 春 记 忆18 小时前
LeetCode 234. 回文链表|Python 解法详解
python·leetcode·链表
AI小码18 小时前
如何让AI帮你构建项目?七级方法
人工智能·算法·计算机·ai·程序员·大模型·编程
1000世界小札18 小时前
排序算法全景总结:从 O(n²) 到 O(n log n),再到线性时间(附完整对比与选型指南)
数据结构·算法·排序算法
一直C19 小时前
【Linux应用编程】深入理解Linux多任务机制:进程原理、状态转换与进程控制实战
linux·开发语言·算法·ubuntu·vim·visual studio code
摇滚侠19 小时前
《SpringBoot 3:入门与应用实战》第 6 章 Spring Boot 最佳实践 阅读笔记 12
android·spring boot·笔记
金立基包装胶水19 小时前
格拉辛纸热封后容易开胶怎么办?
大数据·笔记·其他
玉树临风ives19 小时前
atcoder ABC 472 题解
数据结构·c++·算法
AI服务老曹19 小时前
抽烟识别算法接入 AI 视频分析平台的流程与误报优化指南
人工智能·算法·音视频