剑指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; } };