基于线性表的集合运算
一、实验内容:
假设利用线性表分别表示两个集合A和B(即线性表中的数据元素即为集合中的成员),现要求实现集合的并、交、差运算,即求三个新的集合,分别表示 C = A ∪ B, D = A ∩ B, E = A - B。
二、代码实现
源代码:
#include <iostream>
#include <malloc.h>
#define N 50
typedef int Elemtype;
typedef struct
{
Elemtype data[N];
int length;
}Sqlist;
void Initlist(Sqlist *&L)
{
L = (Sqlist *)malloc(sizeof(Sqlist));
L->length = 0;
}
bool ListInsert(Sqlist *&L, int x, int c)
{
int j;
if (x<1 || x>L->length + 1)
return false;
x--;
for (j = L->length; j > x; --j)
{
L->data[j] = L->data[j - 1];
}
L->data[x] = c;
L->length++;
return true;
}
bool ListEmpty(Sqlist *L)
{
return (L->length == 0);
}
void DispList(Sqlist *L)//输出表
{
int i;
if (ListEmpty(L)) return;
for (i = 0; i < L->length; ++i)
{
printf("%d", L->data[i]);
}
printf("\n");
}
int ListLength(Sqlist *L)
{
return L->length;
}
bool GetElem(Sqlist *L, int x, Elemtype &c)
{
if (x<1 || x>L->length)
return false;
c = L->data[x - 1];
return true;
}
int LocateElem(Sqlist *L, Elemtype e)
{
int i = 0;
while (i<L->length && L->data[i] != e)
i++;
if (i == L->length)
return 0;
else
return i + 1;
}
bool ListDelete(Sqlist *&L, int x, Elemtype &e)
{
int j;
if (x<1 || x >L->length + 1)
return false;
x--;
e = L->data[x];
for (j = x; j < L->length - 1; ++j)
L->data[j] = L->data[j + 1];
L->length--;
return true;
}
void DestroyList(Sqlist *L)
{
free(L);
}
void CreateListR(Sqlist *&L, Elemtype e[], int n)
{
Initlist(L);
int i;
ListInsert(L, 1, e[0]);
for (i = 1; i < n; ++i)
{
if (!LocateElem(L, e[i]))
ListInsert(L, i + 1, e[i]);
}
}
void Union(Sqlist *a, Sqlist *b, Sqlist *&c)
{
Initlist(c);
int i, j, k;
i = 0;
j = 0;
k = 0;
while (i<a->length && j<b->length)
{
if (a->data[i] < b->data[j])
{
ListInsert(c, k + 1, a->data[i]);
k++;
i++;
}
else if (a->data[i] == b->data[j])
{
ListInsert(c, k + 1, a->data[i]);
k++;
i++;
j++;
}
else
{
ListInsert(c, k + 1, b->data[j]);
k++;
j++;
}
}
while (i<a->length)
{
ListInsert(c, k + 1, a->data[i]);
i++;
k++;
}
while (j<b->length)
{
ListInsert(c, k + 1, b->data[j]);
j++;
k++;
}
}
void InsterSect(Sqlist *a, Sqlist *b, Sqlist *&c)
{
DestroyList(c);
Initlist(c);
int i, k;
for (i = 0, k = 0; i < a->length; ++i)
{
if (LocateElem(b, a->data[i]))
{
ListInsert(c, k + 1, a->data[i]);
k++;
}
}
}
void Subs(Sqlist *a, Sqlist *b, Sqlist *&c)
{
DestroyList(c);
Initlist(c);
int i, k;
for (i = 0, k = 0; i < a->length; ++i)
{
if (!LocateElem(b, a->data[i]))
{
ListInsert(c, k + 1, a->data[i]);
k++;
}
ListInsert(c,a->length-k,a->data[i])
}
}
int main()
{
Sqlist *ha, *hb, *hc;
Elemtype a[] = { 1,2,3,4 };
Elemtype b[] = {6,8,2,7,4,1 };
printf("集合的运算如下\n");
CreateListR(ha, a, 4);
CreateListR(hb, b, 6);
printf("第一个集合的元素 : ");
DispList(ha);
printf("第二个集合的元素 : ");
DispList(hb);
Union(ha, hb, hc);
printf("这两个集合的并集C:");
DispList(hc);
InsterSect(ha, hb, hc);
printf("这两个集合的交集C:");
DispList(hc);
Subs(ha, hb, hc);
printf("这两个集合的差集C:");
DispList(hc);
DestroyList(ha);
DestroyList(hb);
DestroyList(hc);
return 0;
}
3.实现效果图: