#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define ERROR 0
#define OVERFLOW -1
#define OK 1;
typedef int Status; /**Status是函数类型,其值是函数结果状态代码,如OK等**/
typedef int ElemType; /*ElemType类型根据实际情况而定,这里假设为char*/
#define MAXSIZE 50 /* 存储空间初始分配量 */
typedef struct
{
ElemType data[MAXSIZE]; /* 数组,存储数据元素 */
int length; /* 表当前有效长度 */
}SqList;
SqList La,Lb;
Status GetElem(SqList L,int i,ElemType *e)
{
/* 初始条件:数组表示的表L已存在,1≤i≤ListLength(L) */
/* 操作结果:用e返回L中第i个数据元素的值,
注意i是指位置,第1个位置的数组是从0开始 */
if(L.length==0 || i<1 || i>L.length)
return ERROR;
*e=L.data[i-1];
return OK;
}
Status ListEmpty(SqList L)
{
/* 初始条件:数组表示的表L已存在。*/
/* 操作结果:若L为空表,则返回TRUE,否则返回FALSE。 */
if(L.length==0)
return TRUE;
else
return FALSE;
}
Status equal(ElemType a,ElemType b)
{
if(a==b) return TRUE;
else return FALSE;
}
int ListLength(SqList L)
{
return L.length;
}
Status ListInsert(SqList *L,int i,ElemType e)
{
ElemType *p,*q;
int j=0;
while((*L).data[j])
{
j++;
}
q=&((*L).data[i-1]);
for(p=&((*L).data[(*L).length-1]);p>=q;--p) *(p+1)=*p;
*q=e;
++(*L).length;
return OK;
}
int LocateElem(SqList L,ElemType e,Status(*compare)(ElemType,ElemType))
{
ElemType *p;
int i=1;//初值为第一个元素的位序
p=L.data;//初值为第一个元素的存储位置
while(i<=L.length&&!compare(*p++,e))
{
++i;
}
if(i<=L.length) return i;
else return 0;
}
void Union(SqList *La,SqList Lb)
{ /* 将所有在表Lb中但不在La中的数据元素插入到La中 */
ElemType e;
int La_len,Lb_len;
int i;
La_len=ListLength(*La); /* 求表La的长度 */
Lb_len=ListLength(Lb);
for(i=1;i<=Lb_len;i++)
{
GetElem(Lb,i,&e); /* 取Lb中第i个数据元素赋给e */
if(!LocateElem(*La,e,equal)) /* La中不存在和e相同的元素,则插入之 */
ListInsert(La,++La_len,e);
}
}
void CreateLise(SqList *L)
{
ElemType ch;
char c='1';
int inlist=FALSE,j;
while(c!='\n')
{
scanf("%d",&ch);
scanf("%c",&c);
for(j=0;j<(*L).length;j++)
{
if(ch==(*L).data[j])
{
inlist=TRUE;
break;
}
else inlist=FALSE;
}
if(!inlist) ListInsert(L,(*L).length+1,ch);
}
}
void Print_Sq(SqList L)
{
int i;
for(i=0;i<L.length;i++)
{
printf(" %d",L.data[i]);
}
if(L.length==0) printf("空集");
printf("\n此集合中的个数 n = %d\n\n",L.length);
}
void Index_Sq()
{
printf("请输入你的第一个集合:");
CreateLise(&La);
printf("集合A为");
Print_Sq(La); //实现表LA的操作
printf("请输入你的第二个集合:");
CreateLise(&Lb);
printf("集合B为");
Print_Sq(Lb); //实现表LB的操作
Union(&La,Lb);
printf("集合A与集合B的并集为:");
Print_Sq(La); //实现表LA与表LB并集的操作
printf("\n");
}
int main()
{
Index_Sq();
return 0;
}
工程实践:求两集和的并集之数组法
最新推荐文章于 2024-06-22 21:53:36 发布