合并有序链表(两条或多条)
1. 合并两个排序的链表
题目链接:合并两个排序的链表
递归版本
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
//两个链表合并,返回头节点
ListNode* Merge(ListNode* p, ListNode* q) {
//递归
//任意一个为空都要返回另一个
if(!p)return q;
if(!q)return p;
if(p->val>q->val)
{
//把小的拿出来,剩下两条链表合并
q->next = Merge(p,q->next);
return q;
}
else
{
p->next = Merge(p->next,q);
return p;
}
}
};
迭代版本
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
//定义结果
ListNode *result = new ListNode(-1),*now;
result->next = nullptr;
now = result;
ListNode *p = new ListNode(-1),*q = new ListNode(-1),*r;
//设置头结点
p->next = pHead1;q->next = pHead2;
//较小的节点插入到结果链表最后
while(p->next&&q->next)
{
if(p->next->val>q->next->val)
{
now->next = q->next;
q->next = q->next->next;
now = now->next;
}
else{
now->next = p->next;
p->next = p->next->next;
now = now->next;
}
}
//可能会有一个链表还有值,拼接起来即可
if(p->next)
{
now->next = p->next;
}
else if(q->next)
{
now->next = q->next;
}
else
{
now->next = nullptr;
}
return result->next;
}
};
2.合并k个已排序的链表
题目链接:合并k个已排序的链表
暴力:将所有链表的节点取出来排序,排完序之后根据值建立新的链表
/**
* 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) {
vector<int> lv;
for(int i=0;i<lists.size();++i)
for(ListNode *p=lists[i];p;p=p->next)
lv.push_back(p->val);
sort(lv.begin(),lv.end());
ListNode *res = new ListNode(-1);
ListNode *now = res;
for(int i=0;i<lv.size();++i)
{
now->next = new ListNode(lv[i]);
now = now->next;
}
return res->next;
}
};
归并排序
/**
* 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) {
return mergeList(lists, 0, lists.size()-1);
}
//合并返回一条新链表的头节点
ListNode *mergeList(vector<ListNode *> &lists,int l,int r){
if(l>r)return nullptr;
//如果只有一个链表,那麽直接返回
if(l==r)return lists[l];
int mid = (l+r)>>1;
//两个链表进行merge,mergeList返回的是一条新链表的头节点
return merge(mergeList(lists, l, mid),mergeList(lists, mid+1, r));
}
ListNode *merge(ListNode *p,ListNode *q)
{
ListNode *h = new ListNode(-1);
ListNode *head = h;
while(p&&q)
{
if(p->val>q->val)
{
h->next = q;
q=q->next;
}
else
{
h->next = p;
p = p->next;
}
h=h->next;
}
if(p)h->next = p;
if(q)h->next = q;
return head->next;
}
};