【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;
}
相关推荐
虎符饼干9 小时前
AI写出的产品介绍与技术文档不一致,品牌知识库应怎样整理事实与使用条件?
笔记
geovindu10 小时前
python:DecisionTree
开发语言·后端·python·算法
geovindu12 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
虎符饼干13 小时前
CMS对接与WebHook内容推送怎样选择?现有建站系统与自建官网的接入条件
笔记
不脱发的程序猿14 小时前
详解UDS CAN诊断:CommunicationControl Service(SID:0x28)
c语言·can·uds·汽车诊断·iso-tp
AllData公司负责人14 小时前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
 梦晓天明14 小时前
1.Spring学习笔记_IOC入门案例
笔记·学习·spring
武子康15 小时前
火系被选七成,就应该削弱吗?
人工智能·算法·机器学习
炸膛坦客16 小时前
单片机/C/C++八股:(三十七)指针数组 和 数组指针
c语言·开发语言·c++