[InterviewBit] Sort List

Sort List

  • Time :
  • Space :
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/

ListNode* merge(ListNode* A, ListNode* B) {
ListNode* dummy = new ListNode(-1);
ListNode* runner = dummy;
while(A and B) {
if(A->val < B->val) {
runner->next = A;
A = A->next;
} else {
runner->next = B;
B = B->next;
}
runner = runner->next;
}
if(A) runner->next = A;
else runner->next = B;

return dummy->next;
}

ListNode* Solution::sortList(ListNode* A) {
vector<ListNode*> AA;
while(A) {
AA.push_back(A);
auto nxt = A->next;
A->next = NULL;
A = nxt;
}
while(AA.size() > 1) {
vector<ListNode*> AAA;
for(int i = 0; i < AA.size(); i += 2) {
if(i + 1 != AA.size()) AAA.push_back(merge(AA[i], AA[i+1]));
else AAA.push_back(AA[i]);
}
swap(AA, AAA);
}
return AA[0];
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/14/PS/interviewbit/sort-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.