leetcode No23. Merge k Sorted Lists

Question:

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

Algorithm:

1、把链表数组合并成一个链表

2、对链表进行排序

这应该不是个好办法、、、仅供参考

Accepted Code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if(head==NULL)
            return NULL;
        if(head->next==NULL)
            return head;
        
        ListNode* pre=head;      //第一段的结尾
        ListNode* p1=head;       //p1一次移动1个结点
        ListNode* p2=head;       //p2一次移动2个结点
        //目标是分成head-pre,p1-p2两段
        while(p2!=NULL && p2->next!=NULL){
            pre=p1;
            p1=p1->next;
            p2=p2->next->next;
        }
        pre->next=NULL;   //head-pre
        
        ListNode* h1=sortList(head);
        ListNode* h2=sortList(p1);
        
        return Merge(h1,h2);
    }
    ListNode* Merge(ListNode* l1,ListNode* l2){
        if(l1==NULL)
            return l2;
        if(l2==NULL)
            return l1;
        if(l1->val < l2->val){
            l1->next=Merge(l1->next,l2);
            return l1;
        }
        else{
            l2->next=Merge(l1,l2->next);
            return l2;
        }
        return NULL;
    }
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if(lists.empty())
            return NULL;
        int k=0;
        while(k<lists.size() && lists[k]==NULL)
            k++;
        if(k==lists.size())
            return NULL;
        ListNode* Head;
        Head=lists[k];
        ListNode* pNode=Head;
        while(pNode->next!=NULL)  //到第一个链表的尾部
            pNode=pNode->next;
        for(int i=k+1;i<lists.size();i++){
            ListNode* curpNode=lists[i];
            while(curpNode!=NULL){
                pNode->next=curpNode;
                curpNode=curpNode->next;
                pNode=pNode->next;
            }
        }
        return sortList(Head);
    }
};


你可能感兴趣的:(LeetCode,链表)