-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path148. Sort List.cpp
More file actions
75 lines (71 loc) · 1.87 KB
/
148. Sort List.cpp
File metadata and controls
75 lines (71 loc) · 1.87 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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
//merge sort
ListNode* sortList(ListNode* head)
{
if(head == NULL || head->next == NULL)
return head;
ListNode* head1 = head;
ListNode* head2 = getMid(head);
head1 = sortList(head1);
head2 = sortList(head2);
return merge(head1, head2);
}
//get the middle of the list
ListNode* getMid(ListNode* head)
{
//guaranteed that at least two nodes
ListNode* fast = head->next;
ListNode* slow = head->next;
ListNode* prev = head;
while(true)
{
if(fast != NULL)
fast = fast->next;
else
break;
if(fast != NULL)
fast = fast->next;
else
break;
prev = slow;
slow = slow->next;
}
prev->next = NULL; // cut
return slow;
}
//merge two list
ListNode* merge(ListNode* head1, ListNode* head2)
{
ListNode* newhead = new ListNode(-1);
ListNode* newtail = newhead;
while(head1 != NULL && head2 != NULL)
{
if(head1->val <= head2->val)
{
newtail->next = head1;
head1 = head1->next;
}
else
{
newtail->next = head2;
head2 = head2->next;
}
newtail = newtail->next;
newtail->next = NULL;
}
if(head1 != NULL)
newtail->next = head1;
if(head2 != NULL)
newtail->next = head2;
return newhead->next;
}
};