《leetCode》:Insertion Sort List

来源:互联网 发布:赵薇杀人知乎 编辑:程序博客网 时间:2024/06/04 19:30

题目

Sort a linked list using insertion sort.

思路

原以为可以直接在链表上利用插入排序来进行,单尝试了半天发现在链表上直接用插入排序有点困难,不可行,因此,就决定将链表中的val保存到一个数组中,然后对数组中的元素进行插入排序,最后进行链表的构建。

说到上面的思路,就有一个关于leetcode关于这个题目是怎么测试的,怎么测试我们有没有用到快排呢???

实现代码如下:

struct ListNode {     int val;     struct ListNode *next;};void insertsortArray(int *nums,int numsSize){    if(nums==NULL||numsSize<=1){        return;    }    for(int i=1;i<numsSize;i++){        int temp=nums[i];        int j=i-1;        for(;j>=0;j--){            if(temp<nums[j]){                nums[j+1]=nums[j];            }            else if(nums[j]<=temp){                nums[j+1]=temp;                break;            }        }        if(j<0){            nums[0]=temp;        }    }}#define N  100000struct ListNode* insertionSortList(struct ListNode* head) {    if(head==NULL||head->next==NULL){        return head;     }     int *value=(int *)malloc(N*sizeof(int));     if(value==NULL){        exit(EXIT_FAILURE);     }     struct ListNode* cur=head;     int index=0;     while(cur!=NULL){        value[index++]=cur->val;        cur=cur->next;     }     //对数组进行插入排序     insertsortArray(value,index);     //重组为链表     head->val=value[0];     head->next=NULL;     struct ListNode *curNode=head;     struct ListNode* node=NULL;     for(int i=1;i<index;i++){        node=(struct ListNode*)malloc(sizeof(struct ListNode));        if(node==NULL){            exit(EXIT_FAILURE);         }         node->val=value[i];         node->next=NULL;//注意:这里要设为NULL,否则不能AC,这个bug卡了我好久         curNode->next=node;         curNode=node;     }     return head;    } 
1 0