17 合并两个排序的链表
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
C++:迭代
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 == NULL) 14 return pHead2 ; 15 if (pHead2 == NULL) 16 return pHead1 ; 17 ListNode* pHead = NULL ; 18 if (pHead1->val <= pHead2->val){ 19 pHead = pHead1 ; 20 pHead1 = pHead1->next ; 21 }else{ 22 pHead = pHead2 ; 23 pHead2 = pHead2->next ; 24 } 25 ListNode* p = pHead ; 26 while(pHead1 != NULL && pHead2 != NULL){ 27 if (pHead1->val <= pHead2->val){ 28 p->next = pHead1 ; 29 pHead1 = pHead1->next ; 30 }else{ 31 p->next = pHead2 ; 32 pHead2 = pHead2->next ; 33 } 34 p = p->next ; 35 } 36 if (pHead1 != NULL) p->next = pHead1 ; 37 if (pHead2 != NULL) p->next = pHead2 ; 38 return pHead ; 39 } 40 };
C++:递归
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 == NULL) 14 return pHead2 ; 15 if (pHead2 == NULL) 16 return pHead1 ; 17 if (pHead1->val <= pHead2->val){ 18 pHead1->next = Merge(pHead1->next , pHead2) ; 19 return pHead1 ; 20 }else{ 21 pHead2->next = Merge(pHead1 , pHead2->next) ; 22 return pHead2 ; 23 } 24 } 25 };