Opening force intersect list (similar to the speed of the pointer movement position of differencing with advanced until the same start pointer)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode* a=headA;
        ListNode* b=headB;
        ListNode* tmp=nullptr;
        int len_a=0;
        int len_b=0;
        int len_sub=0;
        while(a!=nullptr)
        {
            len_a++;
            a=a->next;
        }
        while(b!=nullptr)
        {
            len_b++;
            b=b->next;
        }
        a=headA;
        b=headB;//这里很重要从头开始
        if(len_a>len_b)
        {
            int time=len_a-len_b;
            // for(int i=0;i<time;i++)
            while(time--)
            {
                a=a->next;
            }
        }else{
            int time=len_b-len_a;
            // for(int i=0;i<time;i++)
            while(time--)
            {
                b=b->next;
            }
        }
        while(a&&b)
        {
            if(a==b)
            {
                tmp=a;
                break;
            }
            a=a->next;
            b=b->next;
        }
        return tmp;
    }
};

 

Published 173 original articles · won praise 26 · views 40000 +

Guess you like

Origin blog.csdn.net/weixin_42269817/article/details/105125922