c_cpp 合并k Sorted Listshttp://oj.leetcode.com/problems/merge-k-sorted-lists/

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 合并k Sorted Listshttp://oj.leetcode.com/problems/merge-k-sorted-lists/相关的知识,希望对你有一定的参考价值。

/**
 * 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) {
        if(lists.size() == 0){
            return NULL;
        }
        ListNode *head = NULL;
        bool set_head = false;
        
        ListNode *it;
        int min_i = 0;
        int min_val = 0;
        int i = 0;
        while(true){
            bool set_min = false;
            for(int i = 0; i < lists.size(); i++){
                if(lists[i]){
                    if(!set_min){
                        min_i = i;
                        min_val = lists[i]->val;
                        set_min = true;
                    }
                    else{
                        if(lists[i]->val < min_val){
                            min_i = i;
                            min_val = lists[i]->val;
                        }
                    }
                }
            }
            if(!set_min){
                break;
            }
            ListNode *temp = lists[min_i];
            lists[min_i] = lists[min_i]->next;
            if(!set_head){
                head = temp;
                set_head = true;
                it = head;
            }
            else{
                it->next = temp;
                it = it->next;
                it->next = NULL;
            }
        }
        return head;
    }
};

以上是关于c_cpp 合并k Sorted Listshttp://oj.leetcode.com/problems/merge-k-sorted-lists/的主要内容,如果未能解决你的问题,请参考以下文章

[Leetcode] Merge k sorted lists 合并k个已排序的链表

合并k个排序的列表 Merge k Sorted Lists

Leetcode merge-k-sorted-lists(合并k路有序链表 最小堆)

[LeetCode]23. Merge k Sorted Lists合并K个排序链表

LeetCode 23. 合并K个排序链表(Merge Two Sorted Lists)

LeetCode23. Merge k Sorted Lists