-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path148.Sort List
More file actions
95 lines (87 loc) · 2.75 KB
/
Copy path148.Sort List
File metadata and controls
95 lines (87 loc) · 2.75 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
//solution:
//ÓÃmergesort
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
// determine the num
ListNode* tmp=head;
int listSize=0;
while(tmp!=NULL){
tmp=tmp->next;
listSize++;
}
// determine the loop time;
int halfLen= listSize/2;
if(listSize%2)
halfLen++;
int mergeLen=1;
while(mergeLen<halfLen){
mergeLen *=2;
}
ListNode* nullhead = new ListNode(-1);
nullhead->next = head;
for(int i=1; i<=mergeLen; i=i*2){
ListNode* l1head=nullhead->next;// the merge first list
ListNode* l2head=nullhead->next;// the merge second list
ListNode* oldend = nullhead;
while(l1head!=NULL){
ListNode* preL1=l1head;
ListNode* itrL1=preL1->next;
for(int j=1;j<i&&itrL1!=NULL;j++){
preL1=preL1->next;
itrL1 = itrL1->next;
}// find the l2head, l1end
l2head= itrL1;// l2 head find
if(l2head==NULL){
oldend->next = l1head;
break;
}
preL1->next=NULL;// l1 list formed
ListNode* preL2= l2head;
ListNode* itrL2=preL2->next;
for(int j=1;j<i&&itrL2!=NULL;j++){
preL2=preL2->next;
itrL2 = itrL2->next;
}// find the l2end ,and the new l1head
preL2->next=NULL;// l2 list formed
ListNode* newhead;
ListNode* newend;
mergeTwoLists(l1head,l2head,newhead,newend);
l1head=itrL2;// the l1 head updata
oldend->next=newhead;
oldend = newend;
}
}
return nullhead->next;
}
void mergeTwoLists(ListNode *l1, ListNode *l2,ListNode* &newhead,ListNode* &newend) {
if(l1->val>l2->val) {
swap(l1,l2);
}
ListNode *retList= l1;
while(l1->next!=NULL) {
if(l1->next->val<=l2->val) {
l1= l1->next;
}
else {
ListNode *tmp = l1->next;
l1->next = l2;
l2= tmp;
l1= l1->next;
}
}
l1->next = l2;
while(l2->next!=NULL)
l2=l2->next;
newhead = retList;
newend = l2;
}
};