-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path148.cpp
More file actions
106 lines (83 loc) · 2.45 KB
/
Copy path148.cpp
File metadata and controls
106 lines (83 loc) · 2.45 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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 {
public:
ListNode* recursiveSortList(ListNode* head) {
if (!head || !head->next) return head;
ListNode* left = head;
ListNode* right = getMid(head);
ListNode* temp = right->next;
right->next = nullptr;
right = temp;
left = recursiveSortList(left);
right = recursiveSortList(right);
return merge(left, right);
}
ListNode* iterativeSortList(ListNode* head) {
if (!head || !head->next) return head;
int len = 0;
ListNode* curr = head;
while (curr) {
len++;
curr = curr->next;
}
ListNode* dummy = new ListNode(0, head);
int step = 1;
while (step < len) {
ListNode* prev = dummy;
curr = dummy->next;
while (curr) {
ListNode* left = curr;
ListNode* right = split(left, step);
curr = split(right, step);
ListNode* merged = merge(left, right);
prev->next = merged;
while (prev->next) {
prev = prev->next;
}
}
step *= 2;
}
return dummy->next;
}
private:
ListNode* merge(ListNode* list1, ListNode* list2) {
ListNode* dummy = new ListNode(0);
ListNode* tail = dummy;
while (list1 && list2) {
if (list1->val < list2->val) {
tail->next = list1;
list1 = list1->next;
} else {
tail->next = list2;
list2 = list2->next;
}
tail = tail->next;
}
tail->next = list1 ? list1 : list2;
return dummy->next;
}
ListNode* split(ListNode* head, int step) {
if (!head) return nullptr;
for (int i=0; i<step-1 && head->next; i++) {
head = head->next;
}
ListNode* nextPart = head->next;
head->next = nullptr;
return nextPart;
}
ListNode* getMid(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head->next;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
};