首页 > 代码库 > 【LeetCode】23. Merge k Sorted Lists

【LeetCode】23. Merge k Sorted Lists

合并k个已合并链表。

思路:先把链表两两合并,直到合并至只有一个链表

 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* mergeKLists(vector<ListNode*>& lists) {
12         if(lists.empty()) return NULL;
13         int len = lists.size();
14         while(len>1){
15             for(int i=0;i<len/2;i++){
16                 lists[i] = mergeTwoLists(lists[i],lists[len-1-i]);
17             }
18             len = (len+1)/2;   //这个技巧很有用
19         }
20         return lists.front();
21     }
22     ListNode* mergeTwoLists(ListNode*l1,ListNode*l2){
23         if(NULL==l1) return l2;
24         else if(NULL==l2) return l1;
25         if(l1->val<l2->val){
26             l1->next = mergeTwoLists(l1->next,l2);
27             return l1;
28         }
29         else {
30             l2->next = mergeTwoLists(l1,l2->next);
31             return l2;
32         }
33     }
34 };

 

【LeetCode】23. Merge k Sorted Lists