LeeCode-Insertion Sort List

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;
}
LeeCode-Insertion Sort List_第1张图片

你可能感兴趣的:(LeeCode)