LeetCode #23 合并K个排序链表

直接合并

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeKLists(vector& lists) {
        const int inf=2147483647;
        int j,len,m,k;
        m=sizeof(int);
        len=lists.size();
        ListNode* anshead=new ListNode(0);
        ListNode* p=anshead;
        while(1){
            m=inf;
            for(j=0;jvalval;
                    k=j;
                }
            }
            if(mnext=new ListNode(lists[k]->val);
                p=p->next;
                lists[k]=lists[k]->next;
            }
            else{
                break;
            }
        }
        return anshead->next;
    }
};

分治法(两两合并)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(l1==NULL){
            return l2;
        }
        else if(l2==NULL){
            return l1;
        }
        else if(l1->val>l2->val){
            l2->next=mergeTwoLists(l1,l2->next);
            return l2;
        }
        else{
            l1->next=mergeTwoLists(l1->next,l2);
            return l1;
        }

    }
    ListNode* mergeKLists(vector& lists) {
        ListNode *p1=new ListNode(0);
        ListNode *p2=new ListNode(0);
        if(lists.size()==0){
            return NULL;
        }
        queue dui;
        for(int i=0;i1){
            p1=dui.front();
            dui.pop();
            p2=dui.front();
            dui.pop();
            dui.push(mergeTwoLists(p1,p2));
        }
        return dui.front();
    }
};

你可能感兴趣的:(LeetCode #23 合并K个排序链表)