【Leecode】 Instersection od 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 || !headB)    return nullptr;
        int aLen = 0,bLen = 0;
        int dis = 0;
        ListNode* pA = headA;
        ListNode* pB = headB;
        while(pA){
            pA = pA->next;
            aLen++;
        }
        while(pB){
            pB = pB->next;
            bLen++;
        }
        pA = headA;;
        pB = headB;
        if(aLen >= bLen){
            dis = aLen - bLen;
            while(dis--){
                pA = pA->next;
            }
        }
        if(aLen < bLen){
            dis = bLen - aLen;
            while(dis--){
                pB = pB->next;
            }
        }
        while(pA && pB){
            if(pA == pB)    return pA;
            pA = pA->next;
            pB = pB->next;
        }
        return nullptr;
    }
};

哈哈,终于刷到第50道了!!

posted on 2015-10-08 18:47  泉山绿树  阅读(13)  评论(0)    收藏  举报

导航