描述
给定两个非递减的整数序列A和B,利用链表表示序列A和B,将A和B合并为一个非递增的有序序列C,序列C允许有重复的数据。要求空间复杂度为O(1)。
输入
多组数据,每组数据有三行,第一行为序列A和B的长度n和m,第二行为序列A的n个元素,第三行为序列B的m个元素(元素之间用空格分隔)。n=0且m=0时输入结束。
输出
对于每组数据输出一行,为合并后的序列,每个数据之间用空格分隔。
输入样例 1
5 5
1 3 5 7 9
2 4 6 8 10
5 6
1 2 2 3 5
2 4 6 8 10 12
0 0
输出样例 1
10 9 8 7 6 5 4 3 2 1
12 10 8 6 5 4 3 2 2 2 1
思路:
在上一篇merge的基础上去掉去重的代码,同时采用头插法将链表倒序再输出就行了。
#include<string>
#include<iostream>
#include<map>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
typedef struct LNode
{
int data;
LNode* next;
}*linklist, LNode;
void Init(linklist &l)
{
l = new LNode;
l->next = NULL;
}
void Insert(linklist &l,int n)
{
l = new LNode;
l->next = NULL;
linklist rear = l;
for (int i = 0; i < n; i++)
{
linklist p = new LNode;
cin >> p->data;
p->next = NULL;
rear->next = p;
rear = p;
}
}
void Show(linklist l)
{
linklist p = l;
while (p)
{
cout << p->data << " ";
p = p->next;
}
}
linklist Merge(linklist p1, linklist p2)
{
if (!p1)
return p2;
else if (!p2)
return p1;
if (p1->data < p2->data)
{
p1->next=Merge(p1->next, p2);
return p1;
}
else
{
p2->next=Merge(p1, p2->next);
return p2;
}
}
linklist Reverse(linklist l)
{
linklist p = l, l1;
l1 = new LNode;
l1->data = l->data;
l1->next = NULL;
while (p)
{
linklist q;
q = new LNode;
q->data = p->data;
q->next = l1->next;
l1->next = q;
p = p->next;
}
return l1;
}
int main()
{
linklist l1,l2;
Init(l1);
Init(l2);
int n1, n2;
while(cin >> n1 >> n2&&n1!=0&&n2!=0)
{
Insert(l1, n1);
Insert(l2, n2);
linklist ans=Merge(l1->next, l2->next);
Show(Reverse(ans)->next);
cout << endl;
}
return 0;
}