# leetcode 23. Merge k Sorted Lists

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

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists)
{
//lists的长度
int length = lists.size();
if(length==0)
return NULL;

while(lists.size()>1)
{
ListNode *p,*q;

p=lists.front();
lists.erase(lists.begin());
q=lists.front();
lists.erase(lists.begin());
lists.push_back(merge2Lists(p,q));
}
return lists[0];
}

//根据leetcode 21题的，合并两个排好序的链的方法思路合并
ListNode * merge2Lists(ListNode * p , ListNode * q)
{
if(p==NULL)
return q;
if(q==NULL)
return p;

t1=p;
t2=q;
if(p->val < q->val)
{
t1=t1->next;
tail=p;
}
else
{
t2=t2->next;
tail=q;
}

while(t1!=NULL && t2!=NULL)
{
if(t1->val<t2->val)
{
tail->next=t1;
t1=t1->next;
}
else
{
tail->next=t2;
t2=t2->next;
}
tail=tail->next;
}

if(t1==NULL)
tail->next=t2;
else
tail->next=t1;

}
};                                                                                                                                   // 创建链表
ListNode* CreateList(int A[],int n)
{
if(n <= 0){
}
for(int i = 1;i < n;i++){
ListNode *node = new ListNode(A[i]);
p1->next = node;
p1 = node;
}
}

int main()
{
Solution solution;
vector<ListNode *> vecs;
int A[] = {1,2,4,7,9};
int B[] = {3,5,8,10,11,12};
int C[] = {6,10,13};
int D[] = {15,16,17,23};

// 输出
while(p){
cout<<p->val<<" ";
p = p->next;
}
}<span style="white-space:pre">	</span>

• 本文已收录于以下专栏：

举报原因： 您举报文章：leetcode 23. Merge k Sorted Lists 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)