/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* MergeList(ListNode* & a, ListNode* b) { //合并两个排序链表
ListNode* pa = a;
ListNode* pb = b;
ListNode* c = new ListNode(-1); //哑结点
ListNode* pc = c;
while (pa && pb) {
if (pa->val <= pb->val) {
pc->next = pa;
pc = pc->next;
pa = pa->next;
}
else {
pc->next = pb;
pc = pc->next;
pb = pb->next;
}
}
pc->next = pa ? pa : pb;
return c->next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.empty()) return NULL;
for(int i=1;i<lists.size();i++){ //合并k个排序链表
lists[0]=MergeList(lists[0],lists[i]);
}
return lists[0];
}
};
23.合并K个排序链表
最新推荐文章于 2020-05-31 20:21:07 发布