easy understand 26ms c++ solution


  • -1
    C

    bolded text
    class Solution {
    public:
    void insert(ListNode* &p,ListNode* &r){
    if(r==nullptr)
    return;
    ListNode* temp=p->next;
    p->next=r;
    r->next=temp;
    p=r;
    }
    ListNode* mergeLists(vector<ListNode*>&lists,int start,int end){
    if(end==start){
    if(start<=lists.size()-1)
    return lists[start];
    else{
    return nullptr;
    }
    }
    int mid=(start+end)/2;
    ListNode* p1=mergeLists(lists,start,mid);
    ListNode* p2=mergeLists(lists,mid+1,end);
    ListNode* tails=(ListNode*)malloc(sizeof(ListNode));
    tails->next=nullptr;
    ListNode* head=tails;
    ListNode* temp=nullptr;
    ListNode* it1=p1;
    ListNode it2=p2;
    while(p1&&p2){
    if(p1->val<p2->val){
    temp=p1;
    p1=p1->next;
    temp->next=nullptr;
    insert(tails,temp);
    }
    else{
    temp=p2;
    p2=p2->next;
    temp->next=nullptr;
    insert(tails,temp);
    }
    }
    if(p2!=nullptr){
    tails->next=p2;
    }
    else if(p1!=nullptr){
    tails->next=p1;
    }
    temp=head;
    head=head->next;
    free(temp);
    return head;
    }
    ListNode
    mergeKLists(vector<ListNode*>& lists) {
    if(lists.size()==0){
    return nullptr;
    }
    return mergeLists(lists,0,lists.size()-1);
    }
    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.