d23. Merge k Sorted Lists

来源:互联网 发布:核聚变 知乎 编辑:程序博客网 时间:2024/06/13 20:49

 题目:Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.


用递归两两数组进行合并。


代码:

void sort(struct ListNode** lists,int* number,int listsSize);/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) {        printf("The listsSize is %d\n",listsSize);    if(lists==NULL)    {        printf("Is NULL\n");        return "";    }    int number=1;        sort(lists,&number,listsSize);        return lists[0];}void sort(struct ListNode** lists,int* number,int listsSize){    struct ListNode* l1=lists[0];    struct ListNode* l2=lists[*number];    struct ListNode* pre=NULL;    printf("The number is %d\n",*number);    if(*number>=listsSize)    {        return;    }        if(!l1 && l2)    {        //printf("l1 is NULL\n");        lists[0]=l2;            }    else    {        while(l1!= NULL && l2!=NULL) //放到l1上        {            //printf("whille\n");            int q=l2->val;            int p=l1->val;                      if(q<=p)            {                printf("litter\n");                struct ListNode* savel2=l2->next; //重要                            if(l1==lists[0])                {                    l2->next=l1;                    pre=l2;                                    l1=pre->next;//重要                    lists[0]=l2;                }                else                {                    pre->next=l2;                    pre=l2;                    l2->next=l1;                                    l1=pre->next; //重要                }                            l2=savel2;            }            else            {                pre=l1;                l1=l1->next;            }        }            if(l2)        {            pre->next=l2;            pre=l2;            l2=l2->next;        }    }        (*number)++;    sort(lists,number,listsSize);    }















0 0
原创粉丝点击