[LeetCode] Merge k Sorted Lists

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

Soluton:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        int n = lists.size();
        vector<ListNode *> tmp = lists;
        ListNode *ans = NULL, *e = NULL, *t = NULL;
        bool flag = true;
        while(flag)
        {
            int min = 2147483647, index = 0;
            flag = false;
            
            for(int i = 0;i < n;i++)
            {
                if(tmp[i] != NULL)
                {
                    flag = true;
                    if(tmp[i] -> val < min)
                    {
                        min = tmp[i] -> val;
                        index = i;
                    }
                }
            }
            
            if(flag)
            {
                t = tmp[index] -> next;
                tmp[index] -> next = NULL;
                if(ans == NULL) 
                    {
                        ans = tmp[index];
                        e = ans;
                    }
                else
                    {
                        e -> next = tmp[index];
                        e = e -> next;
                    }
                tmp[index] = t;
            }
            else break;
        }
        
        return ans;
    }
};
posted @ 2014-03-14 19:10  xchangcheng  阅读(127)  评论(0编辑  收藏  举报