1. 程式人生 > >劍指offer-合並兩個排序的鏈表

劍指offer-合並兩個排序的鏈表

tno ide next val spa blog view offer 註意

從小的開始作為頭結點,然後比較選擇較小的進行鏈接

需要註意頭結點確定的時候就要保存下來,因為後面會一直變化往後鏈接新元素

技術分享
/*
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) return pHead2; if(!pHead2) return pHead1; ListNode *ph = NULL, *ph1, *ph2; ph1 = pHead1, ph2 = pHead2; if(ph1->val < ph2->val){ ph = ph1; ph1 = ph1->next; } else{ ph = ph2; ph2
= ph2->next; } ListNode *tmp = ph; while(ph1 && ph2){ if(ph1->val < ph2->val){ ph->next = ph1; ph = ph->next; ph1 = ph1->next; } else{ ph
->next = ph2; ph = ph->next; ph2 = ph2->next; } } if(ph1){ ph->next = ph1; } else if(ph2){ ph->next = ph2; } return tmp; } };
View Code

劍指offer-合並兩個排序的鏈表