(C语言)160.相交链表【LeetCode】

简介: 链表的题,结点题不要空想,要用手画图,然后对着实物图来写代码,思路才清晰

ઇଓ 欢迎来阅读子豪的博客(LeetCode刷题篇)


☾ ⋆有什么宝贵的意见或建议可以在留言区留言


ღღ欢迎 素质三连 点赞 关注 收藏


❣ฅ码云仓库:补集王子 (YZH_skr) - Gitee.com


160. 相交链表 - 力扣(LeetCode)

https://leetcode.cn/problems/intersection-of-two-linked-lists/submissions/


e844ee84777a47eabe20f351ba5e32af.png


思路


O(N^2),先计算两个链表的长度,然后计算长度差,让长的先走差值步


7b46d6f0b9804e1aa86a09e4a573e4c1.png


比较长度


d6fea5f93635497398ab83d775bbb057.png


长的先走


4f2e7da79a944a0caf377118ae8f925d.png


比较结点


01262870cf0c4901bd4aadcb96f294cd.png


struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) 
{
    int lenA = 1, lenB = 1,  X = 1, Max = 1;
    struct ListNode* longList; 
    struct ListNode* cura = headA,* curb = headB;
    while(cura->next)
    {
        ++lenA;
        cura = cura->next;
    }
    while(curb->next)
    {
        ++lenB;
        curb = curb->next;
    }
// X表示长度差值
// Max表示长的那个链表的长度
    if(lenA>lenB)
    {
        X=lenA-lenB;
        while(X--)
        {
            headA = headA->next;
        }
        Max = lenA;
    }
    else
    {
        X=lenB-lenA;
        while(X--)
        {
            headB = headB->next;
        }
        Max = lenB;
    }
    while(Max--)
    {
        if(headA == headB)
        return headA;
        headB = headB->next;
        headA = headA->next;
    }
    return NULL;
}


总结


链表的题,结点题不要空想,要用手画图,然后对着实物图来写代码,思路才清晰

相关文章
|
6天前
LeetCode链表hard 有思路?但写不出来?
LeetCode链表hard 有思路?但写不出来?
|
6天前
|
索引
每日一题:力扣328. 奇偶链表
每日一题:力扣328. 奇偶链表
14 4
|
6天前
leetcode代码记录(移除链表元素
leetcode代码记录(移除链表元素
11 0
|
6天前
|
存储 算法 C语言
C语言刷题~Leetcode与牛客网简单题
C语言刷题~Leetcode与牛客网简单题
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——链表的中间结点
【每日一题】LeetCode——链表的中间结点
|
6天前
|
C语言
链表的插入、删除和查询—C语言
链表的插入、删除和查询—C语言
|
6天前
|
C++
[leetcode 链表] 反转链表 vs 链表相交
[leetcode 链表] 反转链表 vs 链表相交
|
6天前
【力扣】148. 排序链表
【力扣】148. 排序链表
|
C语言
C语言学生信息管理系统链表实现
C语言学生信息管理系统链表实现
145 0
C语言学生信息管理系统链表实现