基于链表的两个非递减有序序列的合并(C++)

描述

给定两个非递减的整数序列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;
}

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值