输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
1 /* 2 struct ListNode { 3 int val; 4 struct ListNode *next; 5 ListNode(int x) : 6 val(x), next(NULL) { 7 } 8 };*/ 9 class Solution { 10 public: 11 ListNode* Merge(ListNode* pHead1, ListNode* pHead2) 12 { 13 if(!pHead1) return pHead2; 14 if(!pHead2) return pHead1; 15 ListNode* res; 16 ListNode* p; 17 if(pHead1->val<pHead2->val) 18 { 19 res=pHead1; 20 pHead1=pHead1->next; 21 } 22 else 23 { 24 res=pHead2; 25 pHead2=pHead2->next; 26 } 27 p=res; 28 while(pHead1&&pHead2){ 29 if(pHead1->val<pHead2->val){ 30 p->next=pHead1; 31 pHead1=pHead1->next; 32 p=p->next; 33 }else{ 34 p->next=pHead2; 35 pHead2=pHead2->next; 36 p=p->next; 37 } 38 } 39 while(pHead1) 40 { 41 p->next=pHead1; 42 pHead1=pHead1->next; 43 p=p->next; 44 } 45 while(pHead2) 46 { 47 p->next=pHead2; 48 pHead2=pHead2->next; 49 p=p->next; 50 } 51 return res; 52 } 53 };