代码改变世界

leetcode - Merge k Sorted Lists

2013-09-13 12:54  张汉生  阅读(198)  评论(0编辑  收藏  举报

题目表述:点击此处

 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 ListNode * merge2Lists(ListNode* list1, ListNode* list2){
10   ListNode * rlt = NULL;
11   ListNode * curNode = NULL;
12   while (list1!=NULL || list2!=NULL){
13     ListNode * lastNode = curNode;
14     if (list1==NULL){
15       curNode = list2;
16       list2 = list2->next;
17     }
18     else if (list2==NULL){
19       curNode = list1;
20       list1=list1->next;
21     }
22     else if (list1->val <= list2->val){
23       curNode = list1;
24       list1 = list1->next;
25     }
26     else {
27       curNode = list2;
28       list2=list2->next;
29     }
30     if (rlt == NULL)
31       rlt = curNode;
32     else
33       lastNode->next = curNode;
34   }
35   return rlt;
36 }
37 
38 struct ListWithSize{
39   int size;
40   ListNode * list;
41 };
42 
43 bool comp(ListWithSize a, ListWithSize b){
44   return a.size > b.size;
45 }
46 
47 class Solution {
48 public:
49   int countSize(ListNode* list){
50     int size = 0;
51     while (list!=NULL){
52       size++;
53       list=list->next; 
54     }
55     return size;
56   }
57   ListNode *mergeKLists(vector<ListNode *> &lists) {
58     // Start typing your C/C++ solution below
59     // DO NOT write int main() function
60     int size = lists.size();
61     if (size<=0)
62       return NULL;
63     ListWithSize * sizeList = new ListWithSize[size+1];
64     for (int i=0; i<size; i++){
65       sizeList[i].size = countSize(lists[i]);
66       sizeList[i].list = lists[i];
67     }
68     make_heap(&sizeList[0], &sizeList[size], comp);
69     for (int i = 1; i<size; i++){
70       pop_heap(&sizeList[0], &sizeList[size-i+1], comp);
71       ListWithSize l1 = sizeList[size-i];
72       pop_heap(&sizeList[0], &sizeList[size-i],comp);
73       ListWithSize l2 = sizeList[size-i-1];
74       ListWithSize lr;
75       lr.size = l1.size + l2.size;
76       lr.list = merge2Lists(l1.list,l2.list);
77       sizeList[size-i-1] = lr;
78       push_heap(&sizeList[0], &sizeList[size-i], comp);
79     }
80     ListNode * rlt = sizeList[0].list;
81     delete []sizeList;
82     return rlt;
83   }
84 };