【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;
}
相关推荐
WBluuue15 分钟前
Codeforces 1087 Div2(ABCDEF)
c++·算法
Yzzz-F40 分钟前
2025 ICPC武汉邀请赛 G [根号分治 容斥原理+DP]
算法
abant21 小时前
leetcode 114 二叉树变链表
算法·leetcode·链表
tankeven1 小时前
HJ165 小红的优惠券
c++·算法
先积累问题,再逐次解决1 小时前
快速幂优美算法
算法
XiYang-DING1 小时前
【LeetCode】 225.用队列实现栈
算法·leetcode·职场和发展
Ztopcloud极拓云视角2 小时前
Gemini 3.1 Pro vs GPT-5.4 Pro:API成本1/3、性能差多少?选型实测笔记
人工智能·笔记·gpt·ai·语言模型
花月C2 小时前
线性动态规划(Linear DP)
算法·动态规划·代理模式
派大星~课堂2 小时前
【力扣-148. 排序链表】Python笔记
python·leetcode·链表