-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sort List.cpp
48 lines (45 loc) · 1.14 KB
/
Sort List.cpp
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
// Sort List
O(nlogn) time and O(1) space with MergeSort
ListNode *sortList(ListNode *head) {
if(head == NULL || head->next == NULL){
return head;
}
ListNode* fast = head;
ListNode* slow = head;
while(fast->next && fast->next->next){
slow = slow->next;
fast = fast->next->next;
}
fast = slow->next;
slow->next = NULL;
slow = sortList(head);
fast = sortList(fast);
ListNode* newHead = NULL;
ListNode* newTail = NULL;
while(slow && fast){
if(slow->val <= fast->val){
if(newHead == NULL){
newHead = slow;
newTail = slow;
}
else{
newTail->next = slow;
newTail = newTail->next;
}
slow = slow->next;
}
else{
if(newHead == NULL){
newHead = fast;
newTail = fast;
}
else{
newTail->next = fast;
newTail = newTail->next;
}
fast = fast->next;
}
}
newTail->next = (slow == NULL)? fast : slow;
return newHead;
}