From 0d2be7eab976c2b084ae74fafd20a9719b1c3595 Mon Sep 17 00:00:00 2001 From: Manuel Pineda Date: Mon, 4 Jan 2021 20:45:31 +0100 Subject: [PATCH] Create 04.cc --- solved/LeetCode/Challenges/2020/January/04.cc | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 solved/LeetCode/Challenges/2020/January/04.cc diff --git a/solved/LeetCode/Challenges/2020/January/04.cc b/solved/LeetCode/Challenges/2020/January/04.cc new file mode 100644 index 00000000..488052cb --- /dev/null +++ b/solved/LeetCode/Challenges/2020/January/04.cc @@ -0,0 +1,50 @@ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + ListNode* tail = (val(l1) < val(l2)) ? l1 : l2; + ListNode* head = tail; + if (tail == l1) { + l1 = advance(l1); + } else { + l2 = advance(l2); + } + + while ((l1 != nullptr) && (l2 != nullptr)) { + ListNode* next = (val(l1) < val(l2)) ? l1 : l2; + if (next == l1) { + l1 = advance(l1); + } else { + l2 = advance(l2); + } + tail->next = next; + tail = advance(tail); + } + + while (l1 != nullptr) { + tail->next = l1; + tail = advance(tail); + l1 = advance(l1); + } + + while (l2 != nullptr) { + tail->next = l2; + tail = advance(tail); + l2 = advance(l2); + } + return head; + } +private: + ListNode* advance(ListNode* l) { + if (l == nullptr) { + return l; + } + return l->next; + } + + int val(ListNode* l) { + if (l == nullptr) { + return 1000; + } + return l->val; + } +};