【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;
}
相关推荐
写代码写到手抽筋3 小时前
5G上行DCI字段判定:端口 流数 PMI选择详解
java·算法·5g
xieliyu.3 小时前
Java算法精讲:双指针(二)
java·开发语言·算法
wayz114 小时前
Momentum:PSL(心理线指标)技术指标详解
算法·金融·数据分析·量化交易·特征工程
8Qi84 小时前
LeetCode 213:打家劫舍 II(House Robber II)—— 题解 ✅
算法·leetcode·职场和发展·动态规划
三品吉他手会点灯5 小时前
C语言学习笔记 - 44.运算符和表达式 - 运算符2 - 除法与取余运算符
c语言·开发语言·笔记·算法
kkeeper~5 小时前
0基础C语言积跬步之动态内存管理
c语言·开发语言
乐迪信息5 小时前
乐迪信息:AI算法盒子实时识别船舶烟雾与火焰异常
大数据·人工智能·算法·安全·目标跟踪
J-Tony115 小时前
【JVM】根可达算法
jvm·算法
艾iYYY5 小时前
string 类的模拟实现
android·服务器·c语言·c++·算法