template <class Type> class Set { //集合的类定义
private:
SetNode <Type> *first, *last; //无序链表的表头指针, 表尾指针
public:
SetList ( ) { first = last = new SetNode <Type>(0); } //构造函数
~SetList ( ) { MakeEmpty ( ); delete first; } //析构函数
void MakeEmpty ( ); //置空集合
int AddMember ( const Type& x ); //把新元素 x 加入到集合之中
int DelMember ( const Type& x ); //把集合中成员 x 删去
Set <Type>& operator = ( Set <Type>& right ); //复制集合 right 到 this。
Set <Type> operator + ( Set <Type>& right ); //求集合 this 与集合 right 的并
Set <Type> operator * ( Set <Type>& right ); //求集合 this 与集合 right 的交
Set <Type> operator - ( Set <Type>& right ); //求集合 this 与集合 right 的差
int Contains ( const Type& x ); //判 x 是否集合的成员
int operator == ( Set <Type>& right ); //判集合 this 与集合 right 相等
Type& Min ( ); //返回集合中的最小元素的值
}
(1) operator + ( )
template <class Type> Set <Type> Set <Type> :: operator + ( Set <Type>& right ) {
//求集合 this 与集合 right 的并, 计算结果通过临时集合 temp 返回,this 集合与 right 集合不变。
SetNode <Type> *pb = right.first->link; //right 集合的链扫描指针
SetNode <Type> *pa, *pc; //this 集合的链扫描指针和结果链的存放指针
Set <Type> temp;
pa = first->link; pc = temp.first;
while ( pa != NULL ) { //首先把集合 this 的所有元素复制到结果链
pc->link = new SetNode<Type> ( pa->data ) ;
pa = pa->link; pc = pc->link;
}
while ( pb != NULL ) { //将集合 right 中元素逐个拿出到 this 中查重
pa = first->link;
while ( pa != NULL && pa->data != pb->data ) pa = pa->link;
if ( pa == NULL ) //在集合 this 中未出现, 链入到结果链
{ pc->link = new SetNode<Type> ( pa->data ); pc = pc->link; }
pb = pb->link;
}
pc->link = NULL; last = pc; //链表收尾
return temp;
}
(2) operator * ( )
template <class Type> Set <Type> Set <Type> :: operator * ( Set <Type>& right ) {
//求集合 this 与集合 right 的交, 计算结果通过临时集合 temp 返回,this 集合与 right 集合不变。
SetNode<Type> *pb = right.first->link; //right 集合的链扫描指针
Set <Type> temp;