#include
#include
#include
#define True 1
#define False 0
#define error do{printf("Init set error!");exit(1);}while(0);
typedef int ElemType;
typedef int Status;
typedef struct NODE{
ElemType data;
struct NODE *next;
}Node;
typedef struct LINKSET{
Node *head;
int len;
}Linkset;
Status initset(Linkset *set)
{
set->head = (Node *)malloc(sizeof(Node));
if(!set->head)
return False;
set->head->next = NULL;
set->len = 0;
return True;
}
Status set_is_member(const Linkset *set,ElemType data)
{
Node *list = set->head->next;
while(list)
{
if(list->data == data)
return False;
list = list->next;
}
return True;
}
Status data_insert(Linkset *set,ElemType data)
{
Node *list = set->head;
Node *node = (Node *)malloc(sizeof(Node));
if(!node)
return False;
node->data = data;
node->next = list->next;
list->next = node;
set->len += 1;
return True;
}
int set_insert(Linkset *set,ElemType data)
{
if(!set_is_member(set,data))
{
return False;
}
return data_insert(set,data);
}
int set_remove(Linkset *set,ElemType data)
{
Node *list1 = set->head->next;
Node *list2 = set->head;
while(list1)
{
if(list1->data == data)
{
list2->next = list1->next;
set->len -= 1;
free(list1);
break;
}
else
{
list1 = list1->next;
list2 = list2->next;
}
}
}
void show_set(Linkset *set)
{
Node *list = set->head->next;
while(list)
{
printf("%d \n",list->data);
list = list->next;
}
printf("number:%d\n",set->len);
}
Linkset *union_set(Linkset *set1,Linkset *set2)
{
Node *list1 = set1->head->next;
Node *list2 = set2->head->next;
Linkset *setu = (Linkset *)malloc(sizeof(Linkset));
if(!setu)
error;
initset(setu);
while(list1)
{
set_insert(setu,list1->data);
list1 = list1->next;
}
while(list2)
{
set_insert(setu,list2->data);
list2 = list2->next;
}
return setu;
}
Linkset *intersection_set(Linkset *set1,Linkset *set2)
{
Node *list1 = set1->head->next;
Node *list2 = set2->head->next;
Linkset *setn = (Linkset *)malloc(sizeof(Linkset));
if(!setn)
error;
initset(setn);
while(list1)
{
if(!set_is_member(set2,list1->data))
{
set_insert(setn,list1->data);
}
list1 = list1->next;
}
return setn;
}
Linkset *different_set(Linkset *set1,Linkset *set2)
{
Node *list1 = set1->head->next;
Node *list2 = set2->head->next;
Linkset *setd = (Linkset *)malloc(sizeof(Linkset));
if(!setd)
error;
initset(setd);
while(list1)
{
if(!set_is_member(set2,list1->data))
{
set_insert(setd,list1->data);
}
list1 = list1->next;
}
return setd;
}
int main()
{
ElemType i = 0;
Linkset set1,set2,*setu,*setn,*setd;
if(!initset(&set1) || !initset(&set2))
error;
for(i= 0;i < 10; i++)
set_insert(&set1,i);
for(i= 5;i < 15; i++)
set_insert(&set2,i);
set_remove(&set1,0);
show_set(&set1);
setu = union_set(&set1,&set2); #set1 u set2
show_set(setu);
setn = intersection_set(&set1,&set2); #set1 n set2
show_set(setn);
setd = different_set(&set1,&set2); #set1 - set2
show_set(setd);
}
阅读(1084) | 评论(0) | 转发(0) |