《劍指offer》——合併兩個排序的鏈表

/*
非遞歸
*/
struct ListNode 
{
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL){}
};

ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
    //如果兩個鏈表中有一個爲空,則返回另一個
    //如果兩個鏈表都爲空,則返回空
    if(pHead1 == NULL)
        return pHead2;
    else if(pHead2 == NULL)
        return pHead1;

    ListNode *pNode1 = pHead1;//遍歷鏈表1的指針
    ListNode *pNode2 = pHead2;//遍歷鏈表2的指針
    ListNode *pHead = NULL;//指向合併後鏈表頭結點的指針
    ListNode *pNode = NULL;//記錄頭結點的指針

    //比較兩個鏈表的第一個結點,找到合併後鏈表的頭結點
    if(pNode1 -> val < pNode2 -> val)
    {
        pHead = pNode1;
        pNode1 = pNode1 -> next;
    }
    else
    {
        pHead = pNode2;
        pNode2 = pNode2 -> next;
    }

    pNode = pHead;//使用合併後鏈表的頭結點

    while(pNode1 && pNode2)//當兩個鏈表都沒有遍歷結束時
    {
        if(pNode1 -> val <= pNode2 -> val)
        {
            pNode -> next = pNode1;//將頭結點指向下一個結點
            pNode = pNode1;//將下一個結點設置爲新的頭結點
            pNode1 = pNode1 -> next;//將遍歷指針後移
        }
        else
        {
            pNode -> next = pNode2;
            pNode = pNode2;
            pNode2 = pNode2 -> next;
        }
    }

    if(pNode1)//如果鏈表1還有剩餘結點
        pNode -> next = pNode1;//將頭結點指向鏈表1剩餘的結點
    if(pNode2)
        pNode -> next = pNode2;

    return pHead;//返回合併後鏈表的頭結點地址
}
/*
遞歸
*/
struct ListNode 
{
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL){}
};

ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
    //如果兩個鏈表中有一個爲空,則返回另一個
    //如果兩個鏈表都爲空,則返回空
    if(pHead1 == NULL)
        return pHead2;
    else if(pHead2 == NULL)
        return pHead1;  

    ListNode *pHead = NULL;//合併後鏈表的頭結點

    //每次循環將頭結點指向新找出來的頭結點
    if(pHead1 -> val < pHead2 -> val)
    {
        pHead = pHead1;
        pHead -> next = Merge(pHead1 -> next, pHead2);
    }
    else
    {
        pHead = pHead2;
        pHead -> next = Merge(pHead1, pHead -> next);
    }

    return pHead;//返回合併後的鏈表的頭結點
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章