题解 | #合并k个已排序的链表#
合并k个已排序的链表
http://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
if(lists.empty())
return nullptr;
int n = lists.size();
while(n>1){
int k = (n+1) / 2;
for(int i=0; i<n/2; i++){
lists[i] = merge(lists[i], lists[i+k]);
}
n = k;
}
return lists[0];
}
ListNode* merge(ListNode* p1, ListNode* p2){
ListNode* dummy = new ListNode(0);
ListNode* cur = dummy;
while(p1 && p2){
if(p1->val > p2->val){
cur->next = p2;
p2 = p2->next;
} else{
cur->next = p1;
p1 = p1->next;
}
cur = cur->next;
}
if(p1) cur->next = p1;
if(p2) cur->next = p2;
return dummy->next;
}
};
https://www.cnblogs.com/grandyang/p/4606710.htmlhttps://www.cnblogs.com/grandyang/p/4606710.html

查看8道真题和解析