-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path148.cpp
More file actions
62 lines (57 loc) · 1.03 KB
/
148.cpp
File metadata and controls
62 lines (57 loc) · 1.03 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
#include<iostream>
#include<cstdio>
#include<cmath>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head==NULL||head->next==NULL)
return head;
ListNode *mid=getMid(head);
ListNode *next=mid->next;
mid->next=NULL;
return merge(sortList(head),sortList(next));
}
ListNode *getMid(ListNode *head)
{
ListNode *fast=head;
ListNode *slow=head;
while(fast->next!=NULL&&fast->next->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
}
return slow;
}
ListNode* merge(ListNode* a,ListNode *b)
{
ListNode *ans=new ListNode(0);
ListNode *node=ans;
while(a!=NULL&&b!=NULL)
{
if(a->val<b->val)
{
node->next=a;
a=a->next;
}else
{
node->next=b;
b=b->next;
}
node=node->next;
}
node->next=(a==NULL)?b:a;
return ans->next;
}
};