#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct set{
int 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("%d",&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("%d ",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;
}//把第一个集合中的元素放在新集合中
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* 求集合的交并差 *");
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");
}
}
可以了
楼上方法是正确的,学习!把分给楼上
2019-07-17 22:53:32