标签:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
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 ListNode* res=NULL; 14 if(pHead1==NULL&&pHead2==NULL) return res; 15 if(pHead1==NULL){ 16 res=pHead2; 17 return res; 18 } 19 if(pHead2==NULL){ 20 res=pHead1; 21 return res; 22 } 23 ListNode* tmp; 24 if(pHead1->val>pHead2->val){ 25 res=pHead2; 26 pHead2=pHead2->next; 27 } 28 29 else{ 30 res=pHead1; 31 pHead1=pHead1->next; 32 } 33 34 tmp=res; 35 while(pHead1!=NULL&&pHead2!=NULL){ 36 if(pHead1->val<pHead2->val){ 37 tmp->next=pHead1; 38 tmp=tmp->next; 39 pHead1=pHead1->next; 40 } 41 else{ 42 tmp->next=pHead2; 43 tmp=tmp->next; 44 pHead2=pHead2->next; 45 } 46 } 47 if(pHead1!=NULL) 48 tmp->next=pHead1; 49 if(pHead2!=NULL) 50 tmp->next=pHead2; 51 return res; 52 } 53 };
标签:
原文地址:http://www.cnblogs.com/zl1991/p/4761849.html