劍指offer【c++】合併兩個排序的鏈表

劍指offer【c++】合併兩個排序的鏈表

題目:輸入兩個單調遞增的鏈表,輸出兩個鏈表合成後的鏈表,當然我們需要合成後的鏈表滿足單調不減規則。

思路:比較簡單,依次迭代

代碼:

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        if (pHead1 == NULL)
            return pHead2;
        if (pHead2 == NULL)
            return pHead1;
        
       
        ListNode* pHead = NULL;
        ListNode* res = NULL;
        
        while(pHead1 != NULL && pHead2 != NULL)
        {
            if (pHead1->val < pHead2->val)
            {
                 if (res == NULL)
                 {
                     pHead = pHead1;
                     res = pHead1;
                 }
                      
                 else
                 {
                     res->next = pHead1;
                     res = res->next;
                 }
                      
           
                 pHead1 = pHead1->next;
             }
            else
            {
                 if(res == NULL)
                 {
                     pHead = pHead2;
                     res = pHead2;
                 }
                      
                 else
                 {
                     res->next = pHead2;
                     res = res->next;
                 }
                      
                 pHead2 = pHead2->next;
            }
        }
        
        if (pHead1 == NULL)
            res->next = pHead2;
        if (pHead2 == NULL)
            res->next = pHead1;
        
        return pHead;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章