有两个链表,怎么求交点

struct ListNode{
int val;
ListNode* next;
ListNode(int x):val(x),next(nullptr);
};

class Solution
{
public:
ListNode* findNode(ListNode* node1,ListNode* node2)
{
    if(node1==nullptr || node2==nullptr)
        return nullptr;
    int len1=0,len2=0;
    ListNode* tmp1=node1,tmp2=node2;
    while(tmp1)
    {
        len1++;
        tmp1=tmp1->next;
    }
    while(tmp2)
    {
        len2++;
        tmp2=tmp2->next;
    }

    tmp1=node1;
    tmp2=node2;
    if(len1next;
    }
    else if(len1>len2)
    {
        for(int i=0;inext;
    }
    while(tmp1 && tmp2)
    {
        if(tmp1==tmp2)
            return tmp1;
        else
        {
            tmp1=tmp1->next;
            tmp2=tmp2->next;
        }
    }
    return nullptr;
}
};

 

你可能感兴趣的:(算法)