-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort list merge sort recursive
96 lines (94 loc) · 2.13 KB
/
sort list merge sort recursive
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
96
/**
* 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==NULL || head->next==NULL)
return head;
ListNode *p=head,*q=head;
while(p->next!=NULL && p->next->next!=NULL){
p=p->next->next;
q=q->next;
}
p=q;
q=q->next;
p->next=NULL;
p=sortList(head);
q=sortList(q);
return merge(p,q);
}
ListNode *merge(ListNode*p,ListNode*q){
ListNode *h=new ListNode(0),*c=h;
while(p!=NULL && q!=NULL){
if(p->val<q->val){
c->next=p;
p=p->next;
c=c->next;
}else{
c->next=q;
q=q->next;
c=c->next;
}
}
if(p!=NULL)
c->next=p;
if(q!=NULL)
c->next=q;
c=h->next;
delete h;
return c;
}
};
/**
* 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==NULL || head->next==NULL)
return head;
ListNode *p=head,*q=head;
while(p->next!=NULL && p->next->next!=NULL){
p=p->next->next;
q=q->next;
}
p=q;
q=q->next;
p->next=NULL;
p=sortList(head);
q=sortList(q);
return merge(p,q);
}
ListNode *merge(ListNode*p,ListNode*q){
ListNode *h=new ListNode(0),*c=h;
while(p!=NULL && q!=NULL){
if(p->val<q->val){
c->next=p;
p=p->next;
c=c->next;
}else{
c->next=q;
q=q->next;
c=c->next;
}
}
if(p!=NULL)
c->next=p;
if(q!=NULL)
c->next=q;
c=h->next;
delete h;
return c;
}
};