【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;
}
相关推荐
Full Stack Developme1 小时前
Java LRU 与 LFU 算法及应用
java·开发语言·算法
Jerry2 小时前
LeetCode 707. 设计链表
算法
疋瓞2 小时前
python和C++对比(1)_数据类型和数据结构
数据结构·c++·python
C语言小火车2 小时前
C++ 堆排序深度精讲:基于完全二叉树的选择排序进化,最坏情况 O(n log n) 的稳定王者
开发语言·c++·算法·排序算法·堆排序
kebidaixu3 小时前
两轮BMS AFE SH367306 I2C 读写时序
算法
智能排队系统_头部供应商3 小时前
RK3588边缘网关改造银行排队系统实战
算法
东方佑3 小时前
临界分词的存在性与最优性:从统计临界态到神经语言模型的双语实证检验
人工智能·算法·语言模型
Fabarta3 小时前
从 0 实现 ChatGPT 风格的流式对话 UI
算法·架构
手写码匠3 小时前
手写 AI 上下文压缩系统:从零实现 Prompt 压缩与选择性上下文管理
人工智能·深度学习·算法·aigc