初阶。
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together
the nodes of the first two lists.
进阶。
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
简洁的方式,使用递归:
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (pHead1 == NULL)
return pHead2;
if (pHead2 == NULL)
<span style="white-space:pre"> </span>return pHead1;
if (pHead1->val < pHead2->val)
{
pHead1->next = Merge(pHead1->next,pHead2);
return pHead1;
}else
{
pHead2->next = Merge(pHead1,pHead2->next);
return pHead2;
}
}
};
#include <iostream>
#include <vector>
using namespace std;
struct LinkNode
{
int data;
LinkNode *next;
LinkNode(int x):data(x),next(nullptr){}
};
LinkNode* mergeTwoList(LinkNode *l1,LinkNode *l2)
{
LinkNode *p1 = l1,*p2 = l2,*head,*pre;
LinkNode *dummy = new LinkNode(-1);
pre = dummy;
while(p1&&p2)
{
if(p1->data < p2->data)
{
pre->next = p1;
p1 = p1->next;
}
else
{
pre->next = p2;
p2 = p2->next;
}
pre = pre->next;
}
if(p1)
pre->next = p1;
if(p2)
pre->next = p2;
head = dummy->next;
delete dummy;
return head;
}
//merge k个list
LinkNode* mergeKList(vector<LinkNode*> &lists)
{
if(lists.size() == 0) return NULL;
LinkNode *p = lists[0];
for(unsigned int i=1;i<lists.size();i++)
{
p = mergeTwoList(p,lists[i]);
}
return p;
}
//对链表初始化
LinkNode *initLink(LinkNode *dummy,int array[],int len)
{
LinkNode *head,*tmp;//dummy表示哑节点,head一般表示头指针,它指向第一个节点。
tmp = dummy;
//用尾插法
for(int i = 0;i < len;i++)
{
LinkNode *p = new LinkNode(array[i]);
tmp->next = p;
tmp = tmp->next;
}
head = dummy->next;
delete dummy;
return head;
}
//显示list
void showList(LinkNode *head)
{
while(head)
{
printf("%d ",head->data);
head = head->next;
}
printf("\n");
}
//摧毁链表
void destroyList(LinkNode *head)
{
LinkNode *dummy = new LinkNode(-1);
dummy->next = head;
LinkNode *pre,*cur,*tmp;
pre = dummy;
cur = pre->next;
while(cur)
{
tmp = cur->next;
pre->next = tmp;
delete cur;
cur = tmp;
}
delete dummy;
printf("The list has been destroyed!\n");
}
void main()
{
LinkNode *dummy1 = new LinkNode(-1);
int array1[] = {1,3,5,7,9};
int len1 = sizeof(array1)/sizeof(int);
LinkNode *head1 = initLink(dummy1,array1,len1);
showList(head1);
LinkNode *dummy2 = new LinkNode(-2);
int array2[] = {2,4,6,8,10,11,12};
int len2 = sizeof(array2)/sizeof(int);
LinkNode *head2 = initLink(dummy2,array2,len2);
showList(head2);
LinkNode *dummy3 = new LinkNode(-3);
int array3[] = {2,7,10,13,15,20,26,33,100,120};
int len3 = sizeof(array2)/sizeof(int);
LinkNode *head3 = initLink(dummy3,array3,len3);
showList(head3);
//LinkNode *head = mergeTwoList(head1,head2);
//showList(head);
vector<LinkNode*> lists;
lists.push_back(head1);
lists.push_back(head2);
lists.push_back(head3);
LinkNode *head = mergeKList(lists);
showList(head);
destroyList(head);
}