forked from moranzcw/LeetCode-NOTES
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.cpp
65 lines (61 loc) · 1.37 KB
/
solution.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* 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)
{
if(!head||!head->next)
return head;
return mergeSort(head);
}
ListNode * mergeSort(ListNode *head)
{
if(!head||!head->next) //just one element
return head;
ListNode *p=head, *q=head, *pre=NULL;
while(q&&q->next!=NULL)
{
q=q->next->next;
pre=p;
p=p->next; //divide into two parts
}
pre->next=NULL;
ListNode *lhalf=mergeSort(head);
ListNode *rhalf=mergeSort(p); //recursive
return merge(lhalf, rhalf); //merge
}
ListNode * merge(ListNode *lh, ListNode *rh)
{
ListNode *temp=new ListNode(0);
ListNode *p=temp;
while(lh&&rh)
{
if(lh->val<=rh->val)
{
p->next=lh;
lh=lh->next;
}
else
{
p->next=rh;
rh=rh->next;
}
p=p->next;
}
if(!lh)
p->next=rh;
else
p->next=lh;
p=temp->next;
temp->next=NULL;
delete temp;
return p;
}
};