[LeetCode] Merge k Sorted Lists

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

类似于Merge Sort的方法做k-1次

 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 *node1, ListNode *node2)
12     {
13         if (node1 == NULL)
14             return node2;
15             
16         if (node2 == NULL)
17             return node1;
18             
19         ListNode *head = NULL;
20         ListNode *curNode = NULL;
21         ListNode *p = node1;
22         ListNode *q = node2;
23         
24         while(p && q)
25         {
26             ListNode *node;
27             if (p->val < q->val)
28             {
29                 node = p;
30                 p = p->next;
31             }
32             else
33             {
34                 node = q;
35                 q = q->next;
36             }
37             
38             if (head == NULL)
39             {
40                 head = curNode = node;
41             }
42             else
43             {
44                 curNode->next = node;
45                 node->next = NULL;
46                 curNode = node;
47             }
48         }
49         
50         if (p)
51         {
52             curNode->next = p;
53         }
54         else if (q)
55         {
56             curNode->next = q;
57         }
58         
59         return head;        
60     }
61     
62     ListNode *mergeKLists(vector<ListNode *> &lists) {
63         // Start typing your C/C++ solution below
64         // DO NOT write int main() function
65         if (lists.size() == 0)
66             return NULL;
67             
68         ListNode *head = lists[0];
69         
70         for(int i = 1; i < lists.size(); i++)
71             head = merge(head, lists[i]);
72             
73         return head;
74     }
75 };

 

 

posted @ 2012-11-18 10:35  chkkch  阅读(1996)  评论(1编辑  收藏  举报