LeetCode_ Merge k Sorted Lists

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

  

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

 *     ListNode(int x) : val(x), next(NULL) {}

 * };

 */

class Solution {

public:

     ListNode *merge(ListNode *head1, ListNode * head2){

        

        if(head1 == NULL) return head2;

        if(head2 == NULL) return head1;

        ListNode *head = new ListNode(2) ;

        ListNode *p, *p1, *p2;

        p = head, p1 = head1, p2 = head2;

        while(p1 != NULL && p2 != NULL){

            if(p1->val < p2->val){

                p->next = p1;

                p = p1;

                p1 = p1->next;

            }else{

                p->next = p2;

                p = p2;

                p2 = p2->next;

            }

        }

        p->next = p1 == NULL ? p2 : p1;

        p = head->next;

        

        delete head;

        return p;

    }

    ListNode *mergeKLists(vector<ListNode *> &lists) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        int n = lists.size();

        if(n < 1) return NULL;

        int len = 1;

        while(len < n){

            for(int i = 0; i + len < n; i += len * 2){

                    lists[i] = merge(lists[i], lists[i+len]);

            }

            len = len<<1;

        }

        return lists[0];

    }

};

归并的思路来做。

你可能感兴趣的:(LeetCode)