forked from pezy/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.h
33 lines (30 loc) · 1.11 KB
/
solution.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <vector>
using std::vector;
#include <cstddef>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode *head = NULL, **lastPtrRef = &head;
for (;l1 && l2; lastPtrRef = &((*lastPtrRef)->next)) {
if (l1->val <= l2->val) { *lastPtrRef = l1; l1 = l1->next; }
else { *lastPtrRef = l2; l2 = l2->next; }
}
*lastPtrRef = l1 ? l1 : l2;
return head;
}
using vecNodeCIter = vector<ListNode *>::const_iterator;
ListNode *mergeKLists(vecNodeCIter beg, vecNodeCIter end) {
if (beg == end) return NULL;
else if (std::distance(beg, end) == 1) return *beg;
else if (std::distance(beg, end) == 2) return mergeTwoLists(*beg, *std::next(beg));
else return mergeTwoLists(mergeKLists(beg, beg + std::distance(beg, end)/2), mergeKLists(beg + std::distance(beg, end)/2, end));
}
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
return mergeKLists(lists.cbegin(), lists.cend());
}
};