Code:
#include<conio.h>
#include<stdio.h>
#include<alloc.h>
typedef int ElementType;
typedef struct Node{
ElementType Element;
Node*Next;
};
typedef struct{
Node*Front;
Node*Rear;
}Queue;
typedef Queue Set;
Set MakeNullSet(){
Queue S;
Node*Header=(Node*)malloc(sizeof(Node));
Header->Next=NULL;
S.Front=Header;
S.Rear=Header;
return S;
}
Node*Make_Node(ElementType X){
Node* P=(Node*)malloc(sizeof(Node));
P->Element=X;
P->Next=NULL;
return P;
}
char Empty_Set(Set S){
return S.Front==S.Rear;
}
int Check(ElementType X,Set S){
Set temp=S;
while(!Empty_Set(temp)){
if(temp.Front->Element == X)
return 1;
else
temp.Front=temp.Front->Next;
}
return 0;
}
void InsertSet(ElementType X,Set &S){
Node *P=Make_Node(X);
if(Check(X,S)==0){
P->Next=S.Rear->Next;
S.Rear->Next=P;
S.Rear=S.Rear->Next;
}
}
void Union(Set A,Set B,Set &C){
Set temp1,temp2;
temp1.Front=A.Front->Next;
temp2.Front=B.Front->Next;
while(temp1.Front!=NULL){
InsertSet(temp1.Front->Element,C);
temp1.Front=temp1.Front->Next;
}
while(temp2.Front!=NULL){
InsertSet(temp2.Front->Element,C);
temp2.Front=temp2.Front->Next;
}
}
void Intersection(Set A,Set B,Set &C){
Set temp;
temp.Front=A.Front->Next;
while(temp.Front!=NULL){
if(Check(temp.Front->Element,B)==1)
InsertSet(temp.Front->Element,C);
temp.Front=temp.Front->Next;
}
}
void Difference(Set A,Set B,Set &C){
Set temp;
temp.Front=A.Front->Next;
while(temp.Front!=NULL){
if(Check(temp.Front->Element,B)==0)
InsertSet(temp.Front->Element,C);
temp.Front=temp.Front->Next;
}
}
Set Input(){
Set S=MakeNullSet();
ElementType X;
printf("\nNhap -1 de ket thuc\n");
do{
scanf("%d",&X);
if(X!=-1)
InsertSet(X,S);
}while(X!=-1);
return S;
}
void Output(Set S){
Set temp=S;
while(!Empty_Set(temp)){
printf("%3d",temp.Front->Next->Element);
temp.Front=temp.Front->Next;
}
}
void Swap(int &a,int &b){
int temp=a;
a=b;
b=temp;
}
void Sort(Set &A){
Set j,i;
i.Front=A.Front->Next;
while(i.Front!=NULL){
j.Front=i.Front->Next;
while(j.Front!=NULL){
if(i.Front->Element>j.Front->Element)
Swap(i.Front->Element,j.Front->Element);
j.Front=j.Front->Next;
}
i.Front=i.Front->Next;
}
}
void main(){
clrscr();
Set A,B,C;
C = MakeNullSet();
printf("\nNhap tap hop A");
A = Input();
Sort(A);
Output(A);
printf("\nNhap tap hop B");
B = Input();
Sort(B);
Output(B);
printf("\nHop cua hai tap hop A va B:");
Union(A,B,C);
Sort(C);
Output(C);
printf("\nGiao cua hai tap hop A va B:");
C = MakeNullSet();
Intersection(A,B,C);
Sort(C);
Output(C);
printf("\nA\\B:");
C = MakeNullSet();
Difference(A,B,C);
Sort(C);
Output(C);
printf("\n");
getch();
}