JZ16 合并两个排序的链表
本文最后更新于:2022年4月9日 中午
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { if (pHead1 == nullptr) return pHead2; else if (pHead2 == nullptr) return pHead1; else if (pHead1->val < pHead2->val) { pHead1->next = Merge(pHead1->next, pHead2); return pHead1; } else { pHead2->next = Merge(pHead1, pHead2->next); return pHead2; } } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { ListNode* dummyHead = new ListNode(-1); ListNode* cur = dummyHead; while (pHead1 && pHead2) { if (pHead1->val < pHead2->val) { cur->next = pHead1; pHead1 = pHead1->next; cur = cur->next; } else { cur->next = pHead2; pHead2 = pHead2->next; cur = cur->next; } } cur->next = pHead1 ? pHead1 : pHead2; return dummyHead->next; } };
|