归并排序递归
struct ListNode* mid(struct ListNode* head);
struct ListNode* merge(struct ListNode* head1,struct ListNode* head2);
struct ListNode* sortInList(struct ListNode* head){
if(head == NULL || head->next == NULL)
return head;
struct ListNode* head1 = head;
struct ListNode* head2 = mid(head);
head1 = sortInList(head1);
head2 = sortInList(head2);
return merge(head1,head2);
}
struct ListNode* mid(struct ListNode* head)
{
struct ListNode* H=malloc(sizeof(struct ListNode));
H->next=head;
struct ListNode* slow = H;
struct ListNode* fast = H;
while(fast != NULL && fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
}
struct ListNode* temp = slow->next;
slow->next = NULL;
return temp;
}
struct ListNode* merge(struct ListNode* head1,struct ListNode* head2)
{
struct ListNode* H =(struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* cur = H;
while(head1 != NULL && head2 != NULL)
{
if(head1->val < head2->val)
{
cur->next = head1;
head1 = head1->next;
}
else
{
cur->next = head2;
head2 = head2->next;
}
cur = cur->next;
}
if(head1!=NULL)
cur->next=head1;
if(head2!=NULL)
cur->next=head2;
return H->next;
}
辅助数组法
int cmp(const void *a,const void *b)
{
return *(int*)a-*(int*)b;
}
struct ListNode* sortInList(struct ListNode* head ) {
int num[1000000];
int i=0;
while(head!=NULL)
{
num[i++]=head->val;
head=head->next;
}
qsort(num, i, sizeof(int), cmp);
struct ListNode* H=malloc(sizeof(struct ListNode));
struct ListNode* cur=H;
int j=0;
while(j!=i)
{
struct ListNode* temp=malloc(sizeof(struct ListNode));
temp->next=NULL;
temp->val=num[j++];
cur->next=temp;
cur=temp;
}
return H->next;
}