链表的各种操作(初始化,建立,销毁,遍历,判断空表,按值查找,按位查找,添加,删除)
·
代码段:
#include<iostream>
#include<cstring>
using namespace std;
class Set
{
private:
char elem[10];
// 判断字符e是否在当前集合内
bool isExist(char e) const
{
for(int i=0; elem[i]!='\0'; i++)
{
if(elem[i] == e)
return true;
}
return false;
}
public:
// 构造函数,初始化集合并自动去重
Set(const char *a = "")
{
memset(elem, 0, sizeof(elem));
int i=0;
while(a[i] != '\0' && i < 9)
{
if(!isExist(a[i]))
elem[i++] = a[i];
}
elem[i] = '\0';
}
// 判断当前集合是否为空集
bool isEmpty() const
{
return elem[0] == '\0';
}
// 输出空集判断结果
void printEmptyTip() const
{
if(isEmpty())
cout << " 是空集" << endl;
else
cout << " 不是空集" << endl;
}
// 向集合添加单个元素,自动去重
void addElem(char e)
{
if(isExist(e)) return;
int len = strlen(elem);
if(len >= 9)
{
cout << "集合已满,无法添加!" << endl;
return;
}
elem[len] = e;
elem[len+1] = '\0';
}
// 删除集合中指定字符元素
void delElem(char e)
{
if(!isExist(e)) return;
int i,j;
int len = strlen(elem);
for(i=0; elem[i]!='\0'; i++)
{
if(elem[i] == e)
{
for(j=i; j<len; j++)
elem[j] = elem[j+1];
break;
}
}
}
// 将源集合完整复制到当前集合
void copySet(const Set &src)
{
strcpy(elem, src.elem);
}
// 打印输出集合全部元素
void showSet() const
{
for(int i=0; elem[i]!='\0'; i++)
cout << elem[i] << " ";
cout << endl;
}
// 求当前集合与另一集合的交集,返回新集合
Set getInter(const Set &b) const
{
char tmp[10] = {0};
int k=0;
for(int i=0; elem[i]!='\0'; i++)
{
if(b.isExist(elem[i]))
tmp[k++] = elem[i];
}
tmp[k] = '\0';
return Set(tmp);
}
// 求当前集合与另一集合的并集,返回新集合
Set getUnion(const Set &b) const
{
char tmp[20] = {0};
int k=0;
for(int i=0; elem[i]!='\0'; i++)
tmp[k++] = elem[i];
for(int i=0; b.elem[i]!='\0'; i++)
{
if(!Set(tmp).isExist(b.elem[i]))
tmp[k++] = b.elem[i];
}
tmp[k] = '\0';
return Set(tmp);
}
// 判断两个集合元素是否完全相等
bool isEqual(const Set &b) const
{
if(strlen(elem) != strlen(b.elem))
return false;
return isSubset(b) && b.isSubset(*this);
}
// 判断当前集合是否为传入集合的子集
bool isSubset(const Set &b) const
{
for(int i=0; elem[i]!='\0'; i++)
{
if(!b.isExist(elem[i]))
return false;
}
return true;
}
};
int main()
{
Set a("abcde");
cout<<"A集合为:"<<endl;
a.showSet();
Set b("abf");
cout<<"B集合为:"<<endl;
b.showSet();
cout<<"集合a是空集吗?";
a.printEmptyTip();
cout<<"创建空集c.....c是空集吗?";
Set c("");
c.printEmptyTip();
cout<<"集合a添加元素z后"<<endl;
a.addElem('z');
a.showSet();
cout<<"删除a中的元素z:"<<endl;
a.delElem('z');
a.showSet();
cout<<"把集合a复制到c中"<<endl;
c.copySet(a);
cout<<"集合c为:"<<endl;
c.showSet();
cout<<"求集合a与集合b的交集:";
Set inter = a.getInter(b);
inter.showSet();
cout<<"求集合a与集合b的并集:";
Set un = a.getUnion(b);
un.showSet();
cout<<endl;
cout<<"判断集合a,b的元素是否完全一样:";
if(a.isEqual(b)) cout<<"相等"<<endl;
else cout<<"不相等"<<endl;
cout<<"判断集合a,c的元素是否完全一样:";
if(a.isEqual(c)) cout<<"相等"<<endl;
else cout<<"不相等"<<endl;
cout<<endl;
cout<<"b是a的子集吗(b为abf,a为abcde):";
if(b.isSubset(a)) cout<<"是子集"<<endl;
else cout<<"不是子集"<<endl;
cout<<"删除b中的f后,集合b为:";
b.delElem('f');
b.showSet();
cout<<"删除b中的f后,b是a的子集吗:";
if(b.isSubset(a)) cout<<"是子集"<<endl;
else cout<<"不是子集"<<endl;
return 0;
}
代码验证:

更多推荐

所有评论(0)