简洁的 集合类 【From My Baidu Space】

#include <iostream.h>

typedef struct node{
 int x;
 struct node *next;
}Node,*pList;

class Set{
private:
 pList m_list;
 int len;
public:
 Set();
 bool IsEmpt();//判断集合是否为空;
 int size();//返回元素的个数;
 bool IsElement(int e) const;//判断e是否属于集合;
 bool IsSubset(const Set & s) const;//判断s是否包含于集合;
 bool IsEqual(const Set & s) const;//判断集合是否相等;
 Set & insert(int e);//将e加入到集合中;
 Set Union(const Set & s) const;//求集合的并;
 Set intersection (const Set & s) const; //求集合的交;
 Set difference (const Set & s) const; //求集合的差;
 void list();
};

Set::Set()
{
 m_list=new Node;
 m_list->next=NULL;
 len=0;
}

bool Set::IsEmpt()
{
  return len==0;
}

int  Set::size()
{
 return len;
}

bool Set::IsElement(int e) const //判断e是否属于集合;
{ pList p=m_list->next;
    while(p && e!=p->x)p=p->next;
 return p!=NULL;
}
bool Set::IsSubset(const Set & s) const //判断s是否包含于集合;
{

 if( len < s.len )return false;
 pList p=s.m_list;
 while(p=p->next)
  if(!IsElement(p->x))return false;
 return true;
}
bool Set::IsEqual(const Set & s) const //判断集合是否相等;
{
 return (len==s.len && IsSubset(s));
}

Set & Set::insert(int e) //将e加入到集合中;
{ pList p=m_list,r;
 while((r=p,p=p->next) && p->x!=e);
 if(!p)
 {
  pList q=new Node;
  q->x=e;
  q->next=NULL;
  r->next=q;
  len++;
 }
 return *this;
}

Set Set::Union(const Set & s) const //求集合的并;
{ pList p=m_list;
 Set q;
 while((p=p->next)!=NULL)q.insert(p->x);
 p=s.m_list;
 while((p=p->next)!=NULL)
  if(!IsElement(p->x))q.insert(p->x);
 return q;
}

Set Set::intersection (const Set & s) const //求集合的交;
{
 pList p=m_list;
 Set q;
 while(p=p->next)
  if(s.IsElement(p->x))q.insert(p->x);
 return q;
}

Set Set::difference (const Set & s) const //求集合的差;
{
 pList p=m_list;
 Set q;
 while(p=p->next)
  if(!s.IsElement(p->x))q.insert(p->x);
 return q;
}
void Set::list()
{
 pList p=m_list;
 while(p=p->next)cout<<p->x<<' ';
 cout<<endl;
}

posted @ 2017-04-06 10:37  dfdqzp  阅读(129)  评论(0编辑  收藏  举报