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&lists) {25 int len = lists.size(), current = len;26 if (len == 0) return NULL;27 queue 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 };