-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort Linkedlist
More file actions
48 lines (48 loc) · 880 Bytes
/
sort Linkedlist
File metadata and controls
48 lines (48 loc) · 880 Bytes
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
ListNode* merge(ListNode *a,ListNode *b)
{
ListNode *h=NULL,*ptr=NULL;
while (a&&b)
{
if (a->val<=b->val)
{
if (!h)h=ptr=a;
else
{
ptr->next=a;
ptr=a;
}
a=a->next;
}
else
{
if (!h)h=ptr=b;
else
{
ptr->next=b;
ptr=b;
}
b=b->next;
}
}
if (a)ptr->next=a;
else ptr->next=b;
return h;
}
ListNode* sortLinkList(ListNode *head) {
int l=0;
ListNode *p=head;
while (p)
{
l++;
p=p->next;
}
if (l<=1)return head;
l/=2;l--;
p=head;
while (l--)p=p->next;
ListNode *t=p->next;
p->next=NULL;
head=sortLinkList(head);
t=sortLinkList(t);
return merge(head,t);
}