#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct set{
char coef;
struct set *next;
}; //线性表的单链表存储结构
void createlist_p(struct set *&p,int n)
{
int i;
struct set *L;
p=(struct set *)malloc(sizeof(set));
p->next=NULL; //建立一个带头结点的单链表
for(i=n;i>0;i--)
{
L=(struct set *)malloc(sizeof(set)); //生成新节点
printf("请输入该集合中第%d个整数元素:",n-i+1);
scanf("%s",&L->coef);
L->next=p->next;
p->next=L; //插入到表头
}
}
void printlist_p(struct set *&p)
{
struct set *L;
int i;
L=p->next;
if(!L) printf("该表为空!\n");
while(L!=NULL)
{
printf("%c ",L->coef);
L=L->next;
i++;
}
printf("\n");
}
void Addset(struct set *&p,struct set *&q,struct set *&r)
{
struct set *k,*m,*n;
r=(struct set *)malloc(sizeof(set));
r->next=NULL;
k=p->next;
for(;k;)
{
m=(struct set *)malloc(sizeof(set));
m->next=r->next;
r->next=m;
m->coef=k->coef;
k=k->next; //r中存放p
}
k=q->next;
m=(struct set *)malloc(sizeof(set));
m->next=r->next;
r->next=m;
m->coef=k->coef;
k=k->next;
for(;k;)
{
for(n=r->next;(k->coef!=n->coef)&&n->next;)
{
n=n->next;
}
if((k->coef!=n->coef)&&!(n->next))
{
m=(struct set *)malloc(sizeof(set));
m->next=r->next;
r->next=m;
m->coef=k->coef;
}
k=k->next;
}
}//求A∪B
void Subset(struct set *&p,struct set *&q,struct set *&r)
{
struct set *k,*m,*n;
r=(struct set *)malloc(sizeof(set));
r->next=NULL;
n=q->next;
for(;n;)
{
m=p->next;
for(;(m->coef!=n->coef)&&m->next;)
{
m=m->next;
}
if(m->coef==n->coef)
{
k=(struct set *)malloc(sizeof(set));
k->next=r->next;
r->next=k;
k->coef=m->coef;
}
n=n->next;
}
}//求A∩B
void Intset(struct set *&p,struct set *&q,struct set *&r)
{
struct set *k,*m,*n;
r=(struct set *)malloc(sizeof(set));
r->next=NULL;
m=p->next;
for(;m;)
{
n=q->next;
for(;(m->coef!=n->coef)&&n->next;)
{
n=n->next;
}
if(!n->next&&(m->coef!=n->coef))
{
k=(struct set *)malloc(sizeof(set));
k->next=r->next;
r->next=k;
k->coef=m->coef;
}
m=m->next;
}
}//求A-B
void bangzhu(){
printf("\n\t\t\t***********************************");
printf("\n\t\t\t\t\* 求集合的交并差 *");
printf("\n\t\t\t***********************************\n");
}
void main()
{
struct set *p,*q,*r;
int m,n,node;
bangzhu();
for(;;)
{
do{
printf("请输入您要选择操作的代码:\n");
printf("1:求两集合的并A∪B\n");
printf("2:求两集合的交A∩B\n");
printf("3:求两集合的差A-B\n");
printf("0:退出该程序\n");
scanf("%d",&node);
} while(node<0||node>3);
if(node==0) exit(1);
printf("\t\t\t/*请输入集合A中元素的个数:*/\n");
scanf("%d",&m);
createlist_p(p,m);
printf("\t\t\t/*请输入集合B中元素的个数:*/\n");
scanf("%d",&n);
createlist_p(q,n);
printf("集合A中元素为:");
printlist_p(p);
printf("集合B中元素为:");
printlist_p(q);
while(node<0||node>3);
switch(node)
{
case 1: Addset( p,q,r);printf("A∪B:\n");printlist_p(r);break;
case 2: Subset( p,q,r);printf("A∩B:\n");printlist_p(r);break;
case 3: Intset(p,q,r); printf("A-B:\n");printlist_p(r);break;
}
printf("\n");
}
}