花了三天时间
实现了算法2-1
不足之处,欢迎指正
问题2-1:假设利用两个线性表LA,LB分别表示两个集合A,B,先要求一个新的集合A=AUB。这就要去对线性表作如下操作:扩大线性表LA,将存在于线性表LB中而不存在与LA中的数据元素插入到线性表LA中去。只要从线性表LB中依次取得每个数据元素,并依值在LA中进行查访,若不存在,则插入之。
//算法2-1 实现A=AUB
#include
#include
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define LISTINCREMENT 2
#define LIST_INIT_SIZE 10
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef int ElemType;
typedef struct
{
ElemType *elem;
int length;
int listsize;
}Sq;
//创建顺序表
Status Init(Sq *L)
{
(*L).elem=(ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if (!(*L).elem)
exit(OVERFLOW);
(*L).length=0;
(*L).listsize=LISTINCREMENT;
return OK;
}
//判断元素关系
Status equal(ElemType c1,ElemType c2)
{
if(c1==c2)
return TRUE;
else
return FALSE;
}
//返回表长
int ListLength(Sq L)
{
return L.length;
}
//插入元素
Status Insert(Sq *L, int i, ElemType e)
{
ElemType *newbase;
int *p, *q;
if (i<1||i>(*L).length+1)
exit(OVERFLOW);
if ((*L).length>=(*L).listsize)
{
newbase=(ElemType *)realloc((*L).elem,((*L).listsize+LISTINCREMENT)*sizeof(ElemType));
if (!newbase)
exit (ERROR);
(*L).elem=newbase;
(*L).listsize+=LISTINCREMENT;
}
q=(*L).elem+i-1;
for (p=(*L).length+(*L).elem-1;p>=q;--p)
*(p+1)=*p;
*q=e;
++(*L).length;
return OK;
}
//打印元素
void print(Sq L, int len)
{
int i;
int *p;
p=L.elem;
for (i=1;i<=len;i++)
printf("%d ", *(p+i-1));
}
//取L的第i个数据元素赋值给e
Status GetElem(Sq L, int i, ElemType *e)
{
if (i<1||i>L.length)
exit(ERROR);
else
*e=*(L.elem+i-1);
return OK;
}
//实现A=AUB
void Union(Sq *La, Sq Lb)
{
ElemType e;
int i;
int La_len, Lb_len;
La_len=ListLength(*La);
Lb_len=ListLength(Lb);//求线性表的长度
for (i=1;i<=Lb_len;i++)//取Lb中第i个数据元素赋给e
{
GetElem(Lb, i, &e);
if (!LocateElem(*La, e, equal))
Insert(La ,++La_len, e);//La中不存在和e相同的数据元素,则插入之
}
}
//在顺序线性表L中查找第1个值与e满足compare()的元素的位序
int LocateElem(Sq L, ElemType e, Status (*compare)(ElemType ,ElemType))
{
//若找到,则返回其在L中的位序,否则返回0
ElemType *p;
int i=1;
p=L.elem;
while (i<=L.length&&!compare(*p++,e))
++i;
if (i<=L.length)
return i;
else
return 0;
}
int main ()
{
Sq La, Lb;
Status i;
int j, k;
int La_len, Lb_len;
int *p, *q;
i=Init(&La);
Init(&Lb);
if(i==1)//创建顺序表成功
//输入元素,输入为0表示终止输入
printf("请输入La的元素(输入0表示终止输入):\n");//输入La的元素
for (j=1,k=1;j!=0;k++)
{
scanf("%d",&j);
if(j!=0)
i=Insert(&La, k ,j);
}
printf("请输入Lb的元素(输入0表示终止输入):\n");//输入Lb的元素
for (j=1,k=1;j!=0;k++)
{
scanf("%d",&j);
if (j!=0)
i=Insert(&Lb, k ,j);
}
La_len=ListLength(La);
Lb_len=ListLength(Lb);
//输出La与Lb的元素
printf("La = ");
print(La, La_len);
printf("\nLb = ");
print(Lb, Lb_len);
Union(&La, Lb);
La_len=ListLength(La);
printf("\nnew La= ");
print(La, La_len);
printf("\n*************Programmed by DXH924***************");
}