题目描述
假设有两个集合 A 和 B 分别用两个线性表 LA 和 LB 表示,即线性表中的数据元素即为集合中的成员。编程实现集合A和集合B的并运算。
输入
第一行为集合A的数据元素个数n 第二行输入n个集合A的数据元素 第三行为集合B的数据元素的个数; 第四行输入m个集合B的数据元素。
输出
第一行为A和B的并集.
样例输入
8
0 5 6 3 8 7 9 10
7
1 3 4 7 8 9 5
样例输出
0 5 6 3 8 7 9 10 1 4
#include<malloc.h>
#include<stdio.h>
#define MaxSize 1000
//用线性表的顺序表存储结构来写
//其实就是两个数组
//但为了符合题目要求,还是用顺序表吧
typedef struct
{
int data[MaxSize];
int length=0;
}SqList;
void Init(SqList*&L)
{
L=(SqList*)malloc(sizeof(SqList));
L->length=0;
}
void Add(SqList*&LA,SqList*&LB)//把最终数据放在LA中
{
int lenA=LA->length;
int lenB=LB->length;
bool flag;
for(int i=0;i<lenB;i++)
{//把LB中的元素在LA中遍历,如果找到就不加入LA,找不到再加
flag=true;//一开始表示"没找到"为真
for(int j=0;j<lenA;j++)
{
if(LB->data[i]==LA->data[j])
{
flag=false;
break;
//在集合A中找到
}
}
if(flag)//如果没找到
{
LA->data[LA->length++]=LB->data[i];
}
}
}
void display(SqList*L)//打表
{
for(int i=0;i<L->length;i++)
{
printf("%d ",L->data[i]);
}
}
int main()
{
SqList *LA,*LB;
Init(LA);
Init(LB);
int n,m;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
//这里下标用LA->length而不用i
//因为在Add函数中会用到LA->length
//所以在这里要更新length的值
scanf("%d",&LA->data[LA->length++]);
}
scanf("%d",&m);
for(int j=0;j<m;j++)
{
scanf("%d",&LB->data[LB->length++]);
}
Add(LA,LB);
display(LA);
}
版权声明:本文为chen10151015原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。