这里使用顺序结构进行操作
首先,创建出头文件:顺序表的一系列基础操作
//shunxubiao.h
#include <stdio.h>
#include <stdlib.h>
#define maxsize 50
typedef int elemtype;
typedef struct Sqlist
{
int Length;
int maxLength;
int* elem;
}Sqlist;
//初始化
int Initlist(Sqlist* L)
{
L->Length = 0;
L->elem = (int*)malloc(sizeof(int) * maxsize);
return 1;
}
//取值
int Getelem(Sqlist L, int i, int* e)
{
if (i<1 || i>L.Length)
return 0;
*e = L.elem[i - 1];
return 1;
}
//查找
int Locateelem(Sqlist L, int e)
{
int i = 0;
for (i = 0; i < L.Length; i++)
{
if (L.elem[i] == e)
return e;
}
if (i == L.Length)
{
return 0;
}
}
//插入
int Listinsert(Sqlist* L, int i, int e)
{
int j = 0;
for (j = L->Length - 1; j >= i - 1; j--)
L->elem[j + 1] = L->elem[j];
L->elem[i - 1] = e;
++L->Length;
return 1;
}
//删除
int Listdel(Sqlist* L, int i)
{
int j = 0;
for (j = i; j <= L->Length; j++)
L->elem[j - 1] = L->elem[j];
--L->Length;
return 1;
}
//求表长
int Listbiaochang(Sqlist L)
{
return L.Length;
}
//打印
void Listprint(Sqlist L)
{
for (int i = 0; i < L.Length; i++)
printf("%5d", L.elem[i]);
}
//销毁
int Listdestory(Sqlist* L)
{
L->Length = 0;
L->maxLength = 0;
free(L->elem);
}
然后,将头文件导入进主文件中,进行集合的运算即可。
1、集合的创建
//创建集合
int Listcreat(Sqlist* L,int i)
{
L->elem[L->Length] = i;
++L->Length;
}
在main函数中使用循环即可将给集合赋值
2、求两个集合的并集
首先取出Lb中的元素,依此查找是否与La中的元素相同;
如果不相同,则把此元素放在La中的最后一位即可。
//求并集
void MergeList(Sqlist* La, Sqlist Lb)
{
int m = Listbiaochang(*La); //求线性表的表长
int n = Listbiaochang(Lb);
int i = 0, e = 0;
for (i = 1; i <= n; i++) //注意这里是<=号!
{
Getelem(Lb, i, &e); //取出Lb中的元素e
if (!Locateelem(*La,e)) //如果不存在与e相同的元素
Listinsert(La,++m,e); //将e插在La的最后
}
}
3、求两个集合的交集
首先定义一个新顺序表Lc,通过查找La,Lb中相同的值,在将此值放入Lc中即可。
//求交集
void jiaoji(Sqlist La, Sqlist Lb, Sqlist* Lc)
{
int e = 0;
int i = 0;
for ( i = 1; i <=La.Length;i++)
{
Getelem(La, i, &e); //获得La中元素的值
if (Locateelem(Lb,e)) //若Lb中有相同的值
{
Lc->elem[Lc->Length] = e; //将值给Lc
++Lc->Length;
}
}
}
完整代码如下:
#include"shunxubiao.h"
//创建集合
int Listcreat(Sqlist* L,int i)
{
L->elem[L->Length] = i;
++L->Length;
}
//求并集
void MergeList(Sqlist* La, Sqlist Lb)
{
int m = Listbiaochang(*La); //求线性表的表长
int n = Listbiaochang(Lb);
int i = 0, e = 0;
for (i = 1; i <= n; i++) //注意这里是<=号!
{
Getelem(Lb, i, &e); //取出Lb中的元素e
if (!Locateelem(*La,e)) //如果不存在与e相同的元素
Listinsert(La,++m,e); //将e插在La的最后
}
}
//求交集
void jiaoji(Sqlist La, Sqlist Lb, Sqlist* Lc)
{
int e = 0;
int i = 0;
for ( i = 1; i <=La.Length;i++)
{
Getelem(La, i, &e); //获得La中元素的值
if (Locateelem(Lb,e)) //若Lb中有相同的值
{
Lc->elem[Lc->Length] = e; //将值给Lc
++Lc->Length;
}
}
}
int main()
{
Sqlist La, Lb, Lc;
Initlist(&La);
Initlist(&Lb);
Initlist(&Lc);
//集合的创建
for (int i = 2; i < 8; i=i+2)
Listcreat(&La, i);
for (int i = 4; i < 8; i++)
Listcreat(&Lb, i);
//交集
jiaoji(La, Lb, &Lc);
printf("交集为:");
Listprint(Lc);
printf("\n");
//并集放后面,因为这里修改了La的值
MergeList(&La, Lb);
printf("并集为:");
Listprint(La); //打印
return 0;
}
结果如下: