求 集合交并和差运算 要求 用线性链表 集合的元素限定为小写 演示程序以用户和计算机的对话方式执行

如题所述

程序如下: #include<stdio.h>
#include<stdlib.h>
typedef struct LNode//定义结构体类型指针
{
char data;
struct LNode*next;
}*pointer;
void Inputdata(pointer head)//定义输入集合函数
{
pointer p;
char tmp;
scanf("%c",&tmp);
while(tmp!='\n')
{
p=(pointer)malloc(sizeof(struct LNode));
p->data=tmp;
p->next=head->next;
head->next=p;
scanf("%c",&tmp);
}
}
void Output(pointer head)//定义输出集合函数
{
pointer p;
p=head->next;
while(p)
{
printf("%c",p->data);
p=p->next;
}
printf("\n");
}
void Add(pointer head1,pointer head2,pointer head3)//定义集合的并集函数
{
pointer p1,p2,p3;
p1=head1->next;
while(p1)
{
p3=(pointer)malloc(sizeof(struct LNode));
p3->data=p1->data;
p3->next=head3->next;
head3->next=p3;
p1=p1->next;
}
p2=head2->next;
while(p2)
{
p1=head1->next;
while((p1)&&(p1->data!=p2->data))
p1=p1->next;
if (!p1)
{
p3=(pointer)malloc(sizeof(struct LNode));
p3->data=p2->data;
p3->next=head3->next;
head3->next=p3;
}
p2=p2->next;
}
}
void Same(pointer head1,pointer head2,pointer head3)//定义集合的交集函数
{
pointer p1,p2,p3;
p1=head1->next;
while(p1)
{
p2=head2->next;
while((p2!=NULL)&&(p2->data!=p1->data))
p2=p2->next;
if((p2!=NULL)&&(p2->data==p1->data))
{
p3=(pointer)malloc(sizeof(struct LNode));
p3->data=p1->data;
p3->next=head3->next;
head3->next=p3;
}
p1=p1->next;
}
}
void Sub(pointer head1,pointer head2,pointer head3)//定义集合的差集函数
{
pointer p1,p2,p3;
p1=head1->next;
while(p1)
{
p2=head2->next;
while((p2)&&(p2->data!=p1->data))
p2=p2->next;
if(!p2)
{
p3=(pointer)malloc(sizeof(struct LNode));
p3->data=p1->data;
p3->next=head3->next;
head3->next=p3;
}
p1=p1->next;
}
} void main()//主函数
{
int n,m;
char str;
printf("输入数据,按回车键结束 (第一个集合必须大于第二个集合)\n");
pointer head1,head2,head3;//声明pointer变量
head1=(pointer)malloc(sizeof(struct LNode));
head1->next=NULL;
head2=(pointer)malloc(sizeof(struct LNode));
head2->next=NULL;
head3=(pointer)malloc(sizeof(struct LNode));
head3->next=NULL; printf("请输入集合1:\n");
Inputdata(head1);//调用输入集合函数
printf("请输入集合2:\n");
Inputdata(head2);//调用输入集合函数
loop:printf("\n请选择正确的操作类型!\n");
printf("1:并集\t2:交集\t3.差集\t4.退出\n请选择序号\n");
for(m=0;;m++)
{
scanf("%d",&n);
switch(n)
{
case 1:
printf("两集合的并是\n");
Add(head1,head2,head3);//调用并集函数
Output(head3);
head3->next=NULL;
break;
case 2:
printf("两集合的交是\n");
Same(head1,head2,head3);//调用交集函数
Output(head3);
head3->next=NULL;
break;
case 3:
printf("两集合的差是\n");
Sub(head1,head2,head3);//调用差集函数
Output(head3);
head3->next=NULL;
break;
case 4:
getchar();
printf("确定要退出吗?< Y Same N >\n");
str=getchar();
if(78==str||110==str)
goto loop;
if(89==str||121==str)
exit(0);
else
printf("错误的指令!\n");
goto loop;
break;
default:
printf("错误的指令!,请重新输入!\n\n");
goto loop;
break;}
}
} 有疑问提出。
温馨提示:答案为网友推荐,仅供参考
相似回答