LeeCode-Insertion Sort List

来源:互联网 发布:2016香港经济发展数据 编辑:程序博客网 时间:2024/06/01 09:14

Sort a linked list using insertion sort.


/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* insertionSortList(struct ListNode* head) {    struct ListNode *p;    p=head;    int count=0;    while(p!=NULL)    {        count++;        p=p->next;    }    int *array;    array=(int *)malloc(count*sizeof(int));    p=head;    int i=0,j,k;    while(p!=NULL)    {        array[i]=p->val;        p=p->next;        i++;    }    for(i=1;i<count;i++)    {        for(j=i-1;j>=0;j--)        {            if(array[j]<array[i])                break;        }        if(j!=i-1)        {            int tmp=array[i];            for(k=i-1;k>j;k--)            {                array[k+1]=array[k];            }            array[k+1]=tmp;        }    }        i=0;    struct ListNode *q;    q=head;    while(q!=NULL)    {        q->val=array[i];        q=q->next;        i++;    }    return head;}


0 0