-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge_K_Sorted_LL.cpp
More file actions
54 lines (50 loc) · 1.11 KB
/
Copy pathMerge_K_Sorted_LL.cpp
File metadata and controls
54 lines (50 loc) · 1.11 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <bits/stdc++.h>
using namespace std;
#define ll long long
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
void sort(ListNode* head) {
for (ListNode* i = head; i != NULL; i = i->next) {
for (ListNode* j = i->next; j != NULL; j = j->next) {
if (i->val > j->val) {
i->val = (i->val) ^ (j->val);
j->val = (i->val) ^ (j->val);
i->val = (i->val) ^ (j->val);
}
}
}
}
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* head = NULL;
if (!lists.size())
return head;
int n = lists.size();
head = lists[0];
ListNode* pre = NULL;
for (int i = 0; i < n - 1; ++i)
{
ListNode* temp = lists[i];
while (temp) {
pre = temp;
temp = temp->next;
}
if (lists[i + 1] != NULL && pre != NULL)
pre->next = lists[i + 1];
else if (lists[i + 1] != NULL && pre == NULL)
head = lists[i + 1];
}
sort(head);
return head;
}
};
int main() {
return 0;
}