1323:算法2-1:集合union

4 篇文章 0 订阅
 

题目描述

假设利用两个线性表LA和LB分别表示两个集合A和B(即:线性表中的数据元素即为集合中的成员),现要求一个新的集合A=A∪B。这就要求对线性表做如下操作:扩大线性表LA,将存在于线性表LB中而不存在于线性表LA中的数据元素插入到线性表LA中去。只要从线性表LB中依次取得每个元素,并依值在线性表LA中进行查访,若不存在,则插入之。上述操作过程可用下列算法描述之。
图:将两个列表合并的算法(C/C++描述)

上图算法中,在第8行取得集合B中的元素,然后再在第10行插入到集合A中。你的任务是先输出集合A和集合B中的元素,每个集合在一行中输出。然后每次在将集合B中的元素取出插入到集合A尾部后输出集合A中的元素。当然你的代码可以和上面的代码不一样,只要有相同的输出即可。

输入格式

有多组测试数据,每组测试数据占两行。第一行是集合A,第一个整数m0<m<=100)代表集合A起始有m个元素,后面有m个整数,代表A中的元素。第二行是集合B,第一个整数n(0<n<=100)代表集合B起始有n个元素,后面有n个整数,代表B中的元素。每行中整数之间用一个空格隔开。

输出

每组测试数据输出n+2行:前两行分别输出集合A、集合B中的数据,后面n行是每次从B中取出元素插入到A尾部后的集合A。每行整数之间用一个空格隔开,每组测试数据之间用一行空行隔开。

样例输入

5 1 5 2 6 3
3 1 7 9
1 3
2 2 7
4 2 5 1 4
4 1 2 4 5

样例输出

1 5 2 6 3
1 7 9
1 5 2 6 3
1 5 2 6 3 7
1 5 2 6 3 7 9

3
2 7
3 2
3 2 7

2 5 1 4
1 2 4 5
2 5 1 4
2 5 1 4
2 5 1 4
2 5 1 4

提示[+]
 
#include "stdio.h"
#include "stdlib.h"
#define List_Size 200
struct data{
	int num;
};
typedef struct
{
	struct data num[List_Size];
	int last;
} SqList;
SqList *Create_List(SqList *L)
{
   L = (SqList  *) malloc (sizeof(SqList));
   L ->last = -1;
   return  L;
}
void Get_Data(SqList *L,int i,int *e)
{
	*e=L->num[i].num;
}
void Insert_List(SqList *L)
{
       struct data d;
       if(L->last  == List_Size-1)
               exit(0);
       else          
       {  
           scanf("%d",&d.num);
           L->last++;
           L ->num[L->last].num = d.num;
       }  
}
void Insert(SqList *L,int e)
{
       if(L->last  == List_Size-1)
              exit(0);
       else          
       {  
           L->last++;
           L ->num[L->last].num = e;
       }  
}
int Locat_Data(SqList *L,int e)
{
	int i;
	for(i=0;i<=L->last;i++)
	{
		if(L->num[i].num==e)
		return 1;
	}
	return 0;
}
void Show_List(SqList *L)
{
	int i;
	for(i=0;i<=L->last;i++)
	 if(i==L->last)
	 printf("%d",L->num[i].num);
	 else
	 printf("%d ",L->num[i].num);
	 printf("\n");
}
 void Fun_Union(SqList *La,SqList *Lb)  
{
	int i,e;
	for(i=0;i<=Lb->last;i++)
	{
	   Get_Data(Lb,i,&e);
	  if(!Locat_Data(La,e))
		  Insert(La,e);
		  Show_List(La); 
	}

}
int main()
{
    int m,n,i,flag;
    while(scanf("%d",&m)!=EOF)
   {
	SqList *La,*Lb;
    La = Create_List(La);
    Lb = Create_List(Lb);
    for(i=0;i<m;i++)
    Insert_List(La);
    scanf("%d",&n);
    for(i=0;i<n;i++)
    Insert_List(Lb);
    Show_List(La);
    Show_List(Lb);
    Fun_Union(La,Lb);
    printf("\n");
   }
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值