标签:color nullptr col targe next 直接 int 连接 www
问题:合并两个排序的链表
要求:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
1 struct ListNode { 2 int val; 3 struct ListNode *next; 4 ListNode(int x) : 5 val(x), next(NULL) { 6 } 7 }; 8 9 class Solution { 10 public: 11 ListNode* Merge(ListNode* pHead1, ListNode* pHead2){ 12 13 } 14 };
解题代码:
递归版:
1 struct ListNode { 2 int val; 3 struct ListNode *next; 4 ListNode(int x) : 5 val(x), next(NULL) { 6 } 7 }; 8 9 class Solution { 10 public: 11 ListNode* Merge(ListNode* pHead1, ListNode* pHead2){ 12 if(pHead1 == nullptr) 13 return pHead2; 14 else if(pHead2 == nullptr) 15 return pHead1; 16 // 两个链表都不为空 17 ListNode *pMerge = nullptr; 18 if(pHead1->val < pHead2->val){ 19 pMerge = pHead1; 20 pMerge->next = Merge(pHead1->next, pHead2); 21 } 22 else{ 23 pMerge = pHead2; 24 pMerge->next = Merge(pHead1, pHead2->next); 25 } 26 return pMerge; 27 } 28 };
非递归版:
1 class Solution { 2 public: 3 ListNode* Merge(ListNode* pHead1, ListNode* pHead2){ 4 if(pHead1 == nullptr) return pHead2; 5 if(pHead2 == nullptr) return pHead1; 6 7 ListNode* pHead = nullptr; 8 if(pHead1->val < pHead2->val){ 9 pHead = pHead1; 10 pHead1 = pHead1->next; 11 } 12 else{ 13 pHead = pHead2; 14 pHead2 = pHead2->next; 15 } 16 ListNode*temp = pHead; 17 // 排序合并,直到较短的链表节点全部遍历完毕 18 while(pHead1 != nullptr && pHead2 != nullptr){ 19 if(pHead1->val < pHead2->val){ 20 temp->next = pHead1; 21 temp = pHead1; 22 pHead1 = pHead1->next; 23 } 24 else{ 25 temp->next = pHead2; 26 temp = pHead2; 27 pHead2 = pHead2->next; 28 } 29 } 30 // 将较长链表的剩余未遍历节点直接连接 31 if(pHead1 == nullptr) 32 temp->next = pHead2; 33 else if(pHead2 == nullptr) 34 temp->next = pHead1; 35 return pHead; 36 } 37 };
标签:color nullptr col targe next 直接 int 连接 www
原文地址:https://www.cnblogs.com/iwangzhengchao/p/9776283.html