两个链表的第一个公共结点

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        if(!pHead1 || !pHead2)
           return NULL;
        
        int length1 = GetLength(pHead1);
        int length2 = GetLength(pHead2);
        
        ListNode *pFast = nullptr;
        ListNode *pSlow = nullptr;
        
        if(length1 >= length2){
            pFast = pHead1;
            pSlow = pHead2;          
        }else{
            pFast = pHead2;
            pSlow = pHead1;
        }
        
        int Diff = abs(length1-length2);
        while(Diff){
            pFast = pFast->next;
            Diff--;
        }
        
        while(pFast && pSlow && pFast != pSlow){
            pFast = pFast->next;
            pSlow = pSlow->next;
        }
        
        return pFast;
   
    }
    
    int GetLength(ListNode *pHead){
        int length = 0;
        while(pHead){
            length++;
            pHead = pHead->next;
        }
        
       return length;
    }
};

 

posted on 2017-02-26 21:41  123_123  阅读(97)  评论(0编辑  收藏  举报