当前位置:网站首页>23. Merge K ascending linked lists -c language

23. Merge K ascending linked lists -c language

2022-07-07 22:03:00 Mr Gao

23. Merge K An ascending list -c Language

Here's an array of linked lists , Each list has been listed in ascending order .

Please merge all the linked lists into one ascending list , Return the merged linked list .

Example 1:

Input :lists = [[1,4,5],[1,3,4],[2,6]]
Output :[1,1,2,3,4,4,5,6]
explain : The linked list array is as follows :
[
1->4->5,
1->3->4,
2->6
]
Combine them into an ordered list to get .
1->1->2->3->4->4->5->6

Example 2:

Input :lists = []
Output :[]

Example 3:

Input :lists = [[]]
Output :[]

The solution code is as follows , Very good topic :

/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */

 struct ListNode* merge(struct ListNode* list1,struct ListNode* list2){
    
     struct ListNode*p=(struct ListNode*)malloc(sizeof(struct ListNode));
     p->next=NULL;
     struct ListNode *s=p;
     if(list1==NULL&&list2){
    
         p->next=list2;
     }
     if(list2==NULL&&list1){
    
         p->next=list1;
     }
     while(list1&&list2){
    
         if(list1->val<list2->val){
    
             p->next=list1;
             p=p->next;
             list1=list1->next;
                if(list1==NULL){
    
                 p->next=list2;
             }
         }
         else{
    
               p->next=list2;
             p=p->next;
             list2=list2->next;
             if(list2==NULL){
    
                 p->next=list1;
             }
         }

     }
     return s->next;;

     
 }


struct ListNode* mergeKLists(struct ListNode** lists, int listsSize){
    
    int i;
    if(listsSize==0){
    
        return NULL;
    }
    struct ListNode *l=lists[0];
    for(i=1;i<listsSize;i++){
    
        l=merge(l,lists[i]);


    }
return l;
}















原网站

版权声明
本文为[Mr Gao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071415029530.html