问题描述:
实现线性单链表类(LinkList),用于表示数据集合,并在此基础上实现连个集合的交运算和并运算(重载*进行交运算,重载+进行并运算)。
代码如下:
#include<iostream>
#include<cstdio>
using namespace std;
class Node{
int data;
Node *next;
public:
Node(){
this->next = NULL;
}
friend class Set;
};
class Set{
Node *head;
public:
Set(){
head = new Node;
}
Set(const Set& a){
head = new Node;
Node *p;
p = a.head->next;
while(p){
insert(p->data);
p=p->next;
}
}
void insert(int x){ //使用insert()方法插入元素
Node *p;
p = head;
while(p->next!=NULL){
if(x == p->next->data)
return; //去重
p = p->next;
}
p->next = new Node;
p->next->data = x;
}
bool isInSet(int x){
Node *p;
p = head->next;
while(p){
if(p->data == x)
return true;
p = p->next;
}
return false;
}
Set operator+(const Set& a){ //重载+进行并运算
Set s;
Node *p;
p = a.head->next;
while(p){
s.insert(p->data);
p=p->next;
}
p = head->next;
while(p){
s.insert(p->data);
p=p->next;
}
return s;
}
Set operator*(const Set& a){ //重载*进行交运算
Set s;
Node *p;
p = a.head->next;
while(p){
if(isInSet(p->data))
s.insert(p->data);
p=p->next;
}
return s;
}
void printSet(){
Node *p;
p = head->next;
printf("{ ");
while(p){
printf("%d ", p->data);
p=p->next;
}
printf("}");
}
};
int main(){
//主函数省略
}