【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;
}
相关推荐
政企项目老覃1 小时前
大模型幻觉治理与自动评测:金融风控场景的落地实践
人工智能·算法·机器学习
是隼人1 小时前
buuctf-pwn inndy_echo(32位fmt)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
淡海水1 小时前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
hansang_IR2 小时前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
xian_wwq2 小时前
【学习笔记】深度认知系列-第16讲-提示词工程
人工智能·笔记·学习
洛阳纸贵2 小时前
MATLAB-matlab基础知识
学习·算法·matlab
落羽的落羽2 小时前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
Nil2082 小时前
leetcode 17电话号码的字母组合
算法·leetcode·职场和发展
刃神太酷啦3 小时前
Redis 进阶核心:持久化 (RDB/AOF)、事务与主从复制全解析----《Hello Redis!》(5)
linux·c语言·数据库·c++·redis·缓存·bootstrap