1. 程式人生 > >劍指offer----合併兩個有序連結串列

劍指offer----合併兩個有序連結串列

題目:合併兩個遞增的有序連結串列。

注意:測試時一定要考慮全面,當兩個連結串列有一個或兩個都為空的情況。

非遞迴:

 ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        if(pHead1==NULL)
            return pHead2;
        if(pHead2==NULL)
            return pHead1;
        ListNode* head=NULL;
        ListNode* cur=NULL;
        if(pHead1->val < pHead2->val)
        {
            
            cur=pHead1;
            head=cur;
            pHead1=pHead1->next;
        }
        else
        {
        	cur=pHead2;
            head=cur;
            pHead2=pHead2->next;
        }
        
        while(pHead1!=NULL&&pHead2!=NULL)
        {
        	if(pHead1->val < pHead2->val)
            {
             	cur->next=pHead1;
                pHead1=pHead1->next;
            }
            else
            {
            	cur->next=pHead2;
                pHead2=pHead2->next;
            }
            cur=cur->next;
            
        }
        if(pHead1!=NULL)	
        {
            cur->next=pHead1;
            
        }
        else
        {
        	cur->next=pHead2;    
            
        }
        return head;
    }

遞迴:

 ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        if(pHead1==NULL)
            return pHead2;
        if(pHead2==NULL)
            return pHead1;
        if(pHead1->val < pHead2->val)
        {
            
            pHead1->next=Merge(pHead1->next,pHead2);
            return pHead1;
          
        }
        else
        {
            pHead2->next=Merge(pHead1,pHead2->next);
            return pHead2;
            
        } 
    }
}