标签:nullptr 存在 style 递增 ext bsp else lis val
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路很朴素,谁小先接上谁。
给出递归和非递归两个版本
class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { // 递归版本 if (!pHead1) return pHead2; if (!pHead2) return pHead1; ListNode* mergeList = nullptr; if (pHead1->val >= pHead2->val){ mergeList = pHead2; mergeList->next = Merge(pHead1, pHead2->next); } else { mergeList = pHead1; mergeList->next = Merge(pHead1->next, pHead2); } return mergeList; } };
class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { // 非递归版本 ListNode* dummy = new ListNode(-1); ListNode* res = dummy; //不同判断p1和p2是否存在,已经处理 while (pHead1 && pHead2){ if (pHead1->val >= pHead2->val) { dummy->next = pHead2; pHead2 = pHead2->next; } else{ dummy->next = pHead1; pHead1 = pHead1->next; } dummy = dummy->next; } dummy->next = pHead1?pHead1:pHead2; return res->next; } };
标签:nullptr 存在 style 递增 ext bsp else lis val
原文地址:https://www.cnblogs.com/shiganquan/p/9341191.html