Intersection of Two Linked Lists

/**
 * 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) {
        if(headA==NULL||headB==NULL) return NULL;
        ListNode *tempA=headA,*tempB=headB;
        int lenA=0,lenB=0,dlen;
        while(tempA!=NULL) {lenA++;tempA=tempA->next;}
        while(tempB!=NULL) {lenB++;tempB=tempB->next;}
        dlen=lenA-lenB>0?lenA-lenB:lenB-lenA;
        if(lenA>=lenB){
            tempA=headA;tempB=headB;
        }
        else {tempA=headB;tempB=headA;}
        while(dlen>0) {tempA=tempA->next;dlen--;}
        while(tempA!=NULL)
        {
            if(tempA==tempB) return tempA;
            else{tempA=tempA->next;tempB=tempB->next;}
        }
        return NULL;
    }
};

你可能感兴趣的:(Intersection of Two Linked Lists)