题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则
解法1:非递归解法
1 class Solution { 2 public: 3 ListNode* Merge(ListNode* pHead1, ListNode* pHead2) 4 { 5 if(!pHead1 && !pHead2)return NULL; 6 if(pHead1 && !pHead2)return pHead1; 7 if(!pHead1 && pHead2)return pHead2; 8 ListNode *newHead; 9 if(pHead1->val < pHead2->val) 10 { 11 newHead=pHead1; 12 pHead1=pHead1->next; 13 }else{ 14 newHead=pHead2; 15 pHead2=pHead2->next; 16 } 17 ListNode *tmp=newHead; 18 while(pHead1 && pHead2) 19 { 20 if(pHead1->val < pHead2->val) 21 { 22 tmp->next=pHead1; 23 tmp=tmp->next; 24 pHead1=pHead1->next; 25 }else{ 26 tmp->next=pHead2; 27 tmp=tmp->next; 28 pHead2=pHead2->next; 29 } 30 } 31 if(pHead1)tmp->next=pHead1; 32 if(pHead2)tmp->next=pHead2; 33 return newHead; 34 } 35 };
解法2:递归解法
1 class Solution { 2 public: 3 ListNode* Merge(ListNode* pHead1, ListNode* pHead2) 4 { 5 if(pHead1==NULL)return pHead2; 6 if(pHead2==NULL)return pHead1; 7 ListNode *newHead; 8 if(pHead1->val < pHead2->val) 9 { 10 newHead=pHead1; 11 newHead->next=Merge(pHead1->next, pHead2); 12 }else{ 13 newHead=pHead2; 14 newHead->next=Merge(pHead1, pHead2->next); 15 } 16 return newHead; 17 } 18 };