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

LeetCode – Refresh – Merge k Sorted Lists

时间:2015-03-21 07:30:23      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

Use merge two looply merge the from the queue.

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *merge(ListNode *l1, ListNode *l2) {
12         if (!l1) return l2;
13         if (!l2) return l1;
14         ListNode *result;
15         if (l1->val < l2->val) {
16             result = l1;
17             result->next = merge(l1->next, l2);
18         } else {
19             result = l2;
20             result->next = merge(l1, l2->next);
21         }
22         return result;
23     }
24     ListNode *mergeKLists(vector<ListNode *> &lists) {
25         int len = lists.size(), current = len;
26         if (len == 0) return NULL;
27         queue<ListNode *> q;
28         for (int i = 0; i < len; i++) {
29             q.push(lists[i]);
30         }
31         while (current > 1) {
32             ListNode *l1 = q.front();
33             q.pop();
34             ListNode *l2 = q.front();
35             q.pop();
36             q.push(merge(l1, l2));
37             current--;
38         }
39         return q.front();
40     }
41 };

 

LeetCode – Refresh – Merge k Sorted Lists

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4355090.html

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