题目:编写一个集合类,实现集合的相应运算。
截图:
源代码:
#include<iostream>
using namespace std;
typedef struct node{
int data;
struct node *next;
}Node,*ptrNode,*list;
class Set{
private:
list L; //采用带头结点的链表存储集合元素
public:
Set()
{
//创建一个头结点
L=(list)new(Node);
L->next=NULL; //存储下一结点信息
L->data=0; //头结点存储集合元素总数
}
~Set() //析构函数,清空所有数据所占内存
{
clear();
}
void ShowElement()
{
ptrNode p=L;
if(!L->next)
{ //如果头结点的指针域为空,则集合为空
cout<<"集合为空!"<<endl;
return;
}
cout<<"元素为:";
while(p->next)
{
p=p->next;
cout<<p->data<<" ";
}
cout<<endl;
}
Set copy()const
{
//得到一个与自身元素相同的类
Set R;
ptrNode p=L;
while(p->next)
{
p=p->next;
(p->data);
}
return R;
}
int size();
bool IsEmpty();
bool IsElement(int e)const;
bool IsSubset(const Set&s)const;
bool IsEqual(const Set&s)const;
Set& insert(int e);
Set& deletElement(int e);
Set Union(const Set&s)const;
Set intersection(const Set&s)const;
Set difference(const Set&s)const;
Set& clear();
int getMax();
int getMin();
Set& upList();
Set& downList();
};
int Set::size()
{
return L->data;
}
bool Set::IsEmpty()
{
if(L->next) //如果头结点的指针域不为空,则集合不为空
return false;
else
return true;
}
bool Set::IsElement(int e)const
{
ptrNode p=L;
while(p->next)
{
//从第二个结点遍历所有元素,找到则返回true
p=p->next;
if(p->data==e)
return true;
}
return false;
}
bool Set::IsSubset(const Set&s)const
{
ptrNode p=;
while(p->next)
{
//依次判断s中的元素是否存在,只要有一个不存在则返回false
p=p->next;
if(!IsElement(p->data))
return false;
}
return true;
}
bool Set::IsEqual(const Set&s)const
{
if(L->data!=->data)
return false;
if(IsSubset(s))
//元素个数相等且是其子集,则两集合相等
return true;
return false;
}
Set& Set::insert(int e)
{
ptrNode p;
if(!IsElement(e))
{
//如果新元素没有重复,则创建新结点插入头结点之后
p=(ptrNode)new(Node);
p->data=e;
p->next=L->next;
L->next=p;
L->data++;
}
return *this;
}
Set& Set::deletElement(int e)
{
int temp=L->data;
c 集合类 来自淘豆网www.taodocs.com转载请标明出处.