*Leetcode 23. 合并K个升序链表
Posted Z-Pilgrim
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了*Leetcode 23. 合并K个升序链表相关的知识,希望对你有一定的参考价值。
/**
* Definition for singly-linked list.
* struct ListNode
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr)
* ListNode(int x) : val(x), next(nullptr)
* ListNode(int x, ListNode *next) : val(x), next(next)
* ;
*/
class Solution
public:
ListNode* merge2List(ListNode*l1, ListNode*l2)
if(!l1) return l2;
if(!l2) return l1;
ListNode *ret = NULL, *tail = NULL;
while(l1 && l2)
ListNode *cur = NULL;
if(l1->val < l2->val)
cur = l1;
l1 = l1->next;
else
cur = l2;
l2 = l2->next;
if(!ret)
ret = tail = cur;
else
tail->next = cur;
tail = tail->next;
if(l1) tail->next = l1;
if(l2) tail->next = l2;
return ret;
ListNode* mergeKLists(vector<ListNode*>& lists, int l, int r)
if(l > r) return NULL;
if(l == r) return lists[l];
if(l + 1 == r) return merge2List(lists[l], lists[r]);
ListNode*l_rslt = mergeKLists(lists, l, l + (r-l)/2);
ListNode*r_rslt = mergeKLists(lists, l+(r-l)/2+1, r);
return merge2List(l_rslt, r_rslt);
ListNode* mergeKLists(vector<ListNode*>& lists)
if(lists.size() == 0) return NULL;
return mergeKLists(lists, 0, lists.size()-1);
;
以上是关于*Leetcode 23. 合并K个升序链表的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode刷题100天—23. 合并K个升序链表(优先队列)—day18