《劍指offer》——兩個鏈表的第一個公共結點

這裏寫圖片描述
這裏寫圖片描述
時間複雜度爲O(m+n)

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

ListNode* FindFirstCommonNode( ListNode *pHead1, ListNode *pHead2) 
{
    ListNode* pFirstCommonNode = NULL;
    if(pHead1 == NULL || pHead2 == NULL)//若輸入鏈表有一個爲空,返回空結點
        return pFirstCommonNode;
    ListNode* pNode1 = pHead1;
    ListNode* pNode2 = pHead2;
    int pLen1 = 0, pLen2 = 0;
    while(pNode1)//分別計算兩個鏈表的長度
    {
        pNode1 = pNode1 -> next;
        pLen1++;
    }
    while(pNode2)
    {
        pNode2 = pNode2 -> next;
        pLen2++;
    }
    int offSet = 0;
    if(pLen1 < pLen2)//移動鏈表的頭結點,將長鏈表的頭結點與短鏈表的頭結點對齊
    {
        offSet = pLen2 - pLen1;
        while(offSet)
        {
            pHead2 = pHead2 -> next;
            offSet--;
        }
    }
    else if(pLen2 < pLen1)
    {
        offSet = pLen1 - pLen2;
        while(offSet)
        {
            pHead1 = pHead1 -> next;
            offSet--;
        }
    }
    while(pHead1 && pHead2)//如果當前結點不相等,則繼續同步遍歷兩個鏈表直到找到第一個公共結點
    {
        if(pHead1 == pHead2)
        {
            pFirstCommonNode = pHead1;
            break;
        }
        else
        {
            pHead1 = pHead1 -> next;
            pHead2 = pHead2 -> next;
        }
    }
    return pFirstCommonNode;//返回第一個公共結點
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章