【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;
}
相关推荐
猫头虎几秒前
什么是ZCode for GLM-5.2?
开发语言·人工智能·python·科技·算法·ai编程·ai写作
依然范特东19 分钟前
强化学习笔记1--基础概念
笔记
长不胖的路人甲27 分钟前
什么是赫夫曼树(哈夫曼树 / Huffman Tree)
python·算法·霍夫曼树
三十岁老牛再出发1 小时前
07.26每日总结
linux·c语言·mysql
Warren2Lynch1 小时前
掌握 UML 构造型、标记定义与标记值:面向领域特定建模的 UML 扩展全面指南
大数据·算法·uml
个 人 练 习 生1 小时前
strcmp与strstr函数的模拟实现
c语言·开发语言·经验分享·学习·程序人生
157092511342 小时前
【无标题】
开发语言·python·算法
稚南城才子,乌衣巷风流2 小时前
换根法(Rerooting)算法详解
算法
小羊先生car2 小时前
RTOS-F429-HAL-基础内容认识(2026/7/26)
c语言
晓梦林2 小时前
[ACTF2020 新生赛]BackupFile学习笔记
android·笔记·学习