码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Merge k Sorted Lists

时间:2015-02-10 16:47:11      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

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

题意:将k个已经排好序的链表合并成一个

思路:用到优先队列比较简单。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
struct cmp{
    bool operator() (ListNode *a, ListNode *b) {
        return a->val > b->val;
    }
};

class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        priority_queue<ListNode *, vector<ListNode *>, cmp> queue;
        for (int i = 0; i < lists.size(); i++) {
            if (lists[i] != NULL)
                queue.push(lists[i]);
        } 

        ListNode *head = NULL, *pre = NULL, *tmp;
        while (!queue.empty()) {
            tmp = queue.top();
            queue.pop();
            if (pre == NULL) head = tmp;
            else pre->next = tmp;
            pre = tmp;

            if (tmp->next != NULL)
                queue.push(tmp->next);
        }

        return head;
    }
};



LeetCode Merge k Sorted Lists

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/43704273

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!