16.合并两个排序链表——剑指offer
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
1 class Solution { 2 public: 3 ListNode* Merge(ListNode* pHead1, ListNode* pHead2) 4 { 5 ListNode* pNew = NULL; 6 ListNode* pCurr = NULL; 7 if (pHead1 == NULL) 8 { 9 return pHead2; 10 } 11 else if (pHead2 == NULL) 12 { 13 return pHead1; 14 } 15 else 16 { 17 while (pHead1 !=NULL && pHead2 !=NULL) 18 { 19 if (pHead1->val <= pHead2->val) 20 { 21 if (pNew == NULL) 22 { 23 pNew = pCurr = pHead1; 24 } 25 else 26 { 27 pCurr->next = pHead1; 28 pCurr = pCurr->next; 29 } 30 pHead1 = pHead1->next; 31 } 32 else 33 { 34 if (pNew == NULL) 35 { 36 pNew = pCurr = pHead2; 37 } 38 else 39 { 40 pCurr->next = pHead2; 41 pCurr = pCurr->next; 42 } 43 pHead2 = pHead2->next; 44 45 } 46 47 } 48 if (pHead1==NULL) 49 { 50 pCurr->next = pHead2; 51 } 52 if (pHead2 == NULL) 53 { 54 pCurr->next = pHead1; 55 } 56 57 } 58 return pNew; 59 } 60 }; 61 62 //递归实现方式: 63 class Solution { 64 public: 65 ListNode* Merge(ListNode* pHead1, ListNode* pHead2) 66 { 67 ListNode* pNew = NULL; 68 69 if (pHead1 == NULL) 70 { 71 return pHead2; 72 } 73 else if (pHead2 == NULL) 74 { 75 return pHead1; 76 } 77 else 78 { 79 if (pHead1->val <= pHead2->val) 80 { 81 pNew = pHead1; 82 pNew->next = Merge(pHead1->next, pHead2); 83 } 84 else 85 { 86 pNew = pHead2; 87 pNew->next = Merge(pHead1, pHead2->next); 88 89 } 90 } 91 92 return pNew; 93 } 94 };

浙公网安备 33010602011771号