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

Merge k Sorted Lists

时间:2014-09-06 14:51:13      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   for   div   sp   log   

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

思路:不断将相邻的链表两两合并,知道只剩一个链表为止。

 1 class Solution {
 2 public:
 3     ListNode *mergeKLists( vector<ListNode *> &lists ) {
 4         if( lists.empty() ) { return 0; }
 5         int size = lists.size();
 6         while( size > 1 ) {
 7             vector<ListNode*> newLists;
 8             for( int i = 0; i < size-1; i += 2 ) {
 9                 newLists.push_back( merge( lists[i], lists[i+1] ) );
10             }
11             if( size % 2 == 1 ) { newLists.push_back( lists[size-1] ); }
12             lists = newLists;
13             size = lists.size();
14         }
15         return lists.front();
16     }
17 private:
18     ListNode* merge( ListNode *node1, ListNode *node2 ) {
19         if( !node1 ) { return node2; }
20         if( !node2 ) { return node1; }
21         ListNode *head = 0, **ppNode = &head;
22         while( node1 && node2 ) {
23             if( node1->val <= node2->val ) {
24                 *ppNode = node1;
25                 node1 = node1->next;
26             } else {
27                 *ppNode = node2;
28                 node2 = node2->next;
29             }
30             ppNode = &((*ppNode)->next);
31         }
32         if( node1 ) {
33             *ppNode = node1;
34         } else {
35             *ppNode = node2;
36         }
37         return head;
38     }
39 };

 

Merge k Sorted Lists

标签:des   style   blog   color   io   for   div   sp   log   

原文地址:http://www.cnblogs.com/moderate-fish/p/3959366.html

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