問題描述:
實現線性單鏈表類(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(){
//主函數省略
}