1. 程式人生 > >《劍指offer》系列 合併兩個排序的連結串列(C++)

《劍指offer》系列 合併兩個排序的連結串列(C++)

連結

題目描述

輸入兩個單調遞增的連結串列,輸出兩個連結串列合成後的連結串列,當然我們需要合成後的連結串列滿足單調不減規則。

思路

兩個連結串列依次比較即可

程式碼

class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        ListNode *pHead3 = new ListNode(0);
        ListNode *temp = pHead3;
        
        while(pHead1!=NULL && pHead2!=NULL)
        {
			if(pHead1->val < pHead2->val)
            {
                
                pHead3->next = pHead1;
                pHead1 = pHead1->next;
                pHead3 = pHead3->next;
                
            }
            else	
            {
                pHead3->next = pHead2;
                pHead2 = pHead2->next;
                pHead3 = pHead3->next;
                
			}
        }
        if(pHead1!=NULL)
            pHead3->next = pHead1;
        if(pHead2!=NULL)
            pHead3->next = pHead2;
        return temp->next;
    }
};