采用顺序表表示集合,编程求集合运算(A-B) ∪(B-A)的结果。
例:设集合A=(c,b,e,g,f,d),B=(a,b,n,f),则(A-B) ∪(B-A)=(c,e,g,d,a,n)
#include <iostream>
#define ok 1
#define error 0
#define overflow -2
#define MaxSize 100
using namespace std;
typedef char ElemType;
typedef int Status;
//定义
typedef struct
{
ElemType *elem;
int length;
}SqList;
//函数声明
Status InitList(SqList &L);
Status Empty(SqList L);
Status CreateList(SqList &L, int n);
Status ListInsert(SqList &L, int i, ElemType e);
Status LocateElem(SqList L, ElemType e);
Status DispList(SqList L);
Status A_BList(SqList LA, SqList LB);
Status Union(SqList LA, SqList LB, SqList &LC);
int main()
{
int n1, n2;
SqList L;
InitList(L);
SqList LA;
InitList(LA);
cout << "how mang elements in A?" << endl;
cin >> n1 ;
cout << "Input A:" << endl;
CreateList(LA, n1);
SqList LB;
InitList(LB);
cout << "how many elements in B?" << endl;
cin >> n2 ;
cout << "Input B:" << endl;
CreateList(LB, n2);
cout << "******************************* " << endl;
cout << "A is :" << ' ';
DispList(LA);
cout << endl;
cout << "B is :" << ' ' ;
DispList(LB);
cout << endl;
cout << "A - B is :";
A_BList(LA, LB);
cout << endl;
cout << "B - A is :";
A_BList(LB, LA);
cout << endl;
cout << "(A-B) ∪(B-A) is : ";
A_BList(LA, LB);
A_BList(LB, LA);
cout << endl;
}
//初始化
Status InitList(SqList &L)
{
L.elem = new ElemType[MaxSize];
if (!L.elem)
exit(overflow);
else
L.length = 0;
return ok;
}
//判空
Status Empty(SqList L)
{
return (L.length == 0);
}
//创建
Status CreateList(SqList &L, int n)
{
for (int i = 0; i < n; i++)
cin >> L.elem[i];
L.length = n;
return ok;
}
//插入
Status ListInsert(SqList &L, int i, ElemType e)
{
if (i < 1 || i > L.length) //判断合法性
return error;
if (L.length == MaxSize)
return error;
for (int j = L.length; j >= i; j--)
L.elem[j] = L.elem[j - 1]; //插入操作
L.elem[i] = e;
L.length++;
return ok;
}
//按值查找
Status LocateElem(SqList L, ElemType e)
{
for (int i = 0; i < L.length ;i++)
{
if (L.elem[i] == e)
return (i + 1); //找到了就返回位序
}
return error; //查找失败,返回error
}
//输出
Status DispList(SqList L)
{
for (int i = 0; i < L.length; i++)
cout << L.elem[i] << ' ';
return ok;
}
//A - B
Status A_BList(SqList LA, SqList LB)
{
for (int i = 0; i < LA.length; i++)
{
if (!(LocateElem(LB, LA.elem[i]))) //查找LA和LB表中是否有相同元素
cout << LA.elem[i] << ' '; //如果有不相同的就输出LA的元素
return ok;
}
//销毁
Status DeleteList(SqList &L)
{
delete []L.elem;
L.elem = NULL;
L.length = 0;
return ok;
}
顺序表求集合运算(A-B) ∪(B-A)
最新推荐文章于 2023-06-09 11:03:09 发布