【LeetCode】相交链表

ぐ巨炮叔叔 提交于 2020-02-08 02:49:13

题目描述

编写一个程序,找到两个单链表相交的起始节点。
如下面的两个链表:
在这里插入图片描述
在节点 c1 开始相交。
示例1:
在这里插入图片描述
示例2:
在这里插入图片描述
示例3:
在这里插入图片描述
注意:
1、如果两个链表没有交点,返回 null。
2、在返回结果后,两个链表仍须保持原有的结构。
3、可假定整个链表结构中没有循环。
4、程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。

完整代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    int lenA = 0;
    int lenB = 0;
    struct ListNode* curA = headA;
    struct ListNode* curB = headB;
    while(curA && curA->next != NULL)
    {
        lenA++;
        curA = curA->next;
    }
    while(curB && curB->next != NULL)
    {
        lenB++;
        curB = curB->next;
    }
    if(curA != curB)
    {
        return NULL;
    }
    else
    {
        int gap = abs(lenA-lenB);
        struct ListNode *longlist = headA;
        struct ListNode *shortlist = headB;
        if(lenB > lenA)
        {
            longlist = headB;
            shortlist = headA;
        }
        while(gap--)
        {
            longlist = longlist->next;
        }
        while(1)
        {
            if(longlist == shortlist)
            {
                return longlist;
            }
            else
            {
                longlist = longlist->next;
                shortlist = shortlist->next;
            }
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!