集合的交、并、差运算
【问题描述】
编制一个能演示执行集合的交、并和差运算的程序。
【任务要求】
基本要求:集合元素用小写英文字母,执行各种操作应以对话方式执行。
算法要点:利用单链表表示集合;理解好三种运算的含义
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct PNode //构造结构体
{
char data;
struct PNode* next;
}*PLinklist, node;
PLinklist head;
int Init(PLinklist head)
{
head=(PLinklist)malloc(sizeof(PNode));
if(head)
{
(head)->next=NULL;
return 1;
}
else
return 0;
}
void printflist(PLinklist head) //输入链表
{
PLinklist L;
char t;
scanf("%c", &t);
while(t!='#')
{
L=(PNode*)malloc(sizeof(PNode));
L->data=t;
L->next=head->next;
head->next=L;
scanf("%c",&t);
}
}
void putlist(PLinklist head) //输出链表
{
PLinklist L;
L=head->next;
while(L!=NULL)
{
printf("%c",L->data);
L=L->next;
}
printf("\n");
}
void binji(PLinklist head1,PLinklist head2,PLinklist head3) //求并集
{
PLinklist h1;
PLinklist h2;
PLinklist h3;
h1=head1->next;
while(h1!=NULL)
{
h3=(PNode*)malloc(sizeof(PNode));
h3->data=h1->data;
h3->next=head3->next;
head3->next=h3;
h1=h1->next;
}
h2=head2->next;
while(h2!=NULL)
{
h1=head1->next;
while((h1!=NULL)&&(h1->data!=h2->data))
{
h1=h1->next;
if(h1==NULL)
{
h1=(PNode*)malloc(sizeof(PNode));
h1->data=h2->data;
h1->next=head3->next;
head3->next=h1;
}
}
h2=h2->next;
}
}
void jiaoji(PLinklist head1,PLinklist head2,PLinklist head3) //求交集
{
PLinklist h1;
PLinklist h2;
PLinklist h3;
h1=head1->next;
while (h1!=NULL)
{
h2=head2->next;
while((h2!=NULL)&&(h2->data!=h1->data))
{
h2=h2->next;
if ((h2!=NULL)&&(h2->data==h1->data))
{
h3=(PNode*)malloc(sizeof(PNode));
h3->data=h1->data;
h3->next=head3->next;
head3->next=h3;
}
}
h1=h1->next;
}
}
void chaji(PLinklist head1,PLinklist head2,PLinklist head3) //求差集
{
PLinklist h1;
PLinklist h2;
PLinklist h3;
h1=head1->next;
while (h1!=NULL)
{
h2=head2->next;
while((h2!=NULL)&&(h1->data!=h2->data))
{
h2=h2->next;
if(h2==NULL)
{ h3=(PNode*)malloc(sizeof(PNode));
h3->data=h1->data;
h3->next=head3->next;
head3->next=h3;
}
}
h1=h1->next;
}
}
int main()
{
int i;
PLinklist head1;
PLinklist head2;
PLinklist head3;
head1=(PNode*)malloc(sizeof(PNode)); head1->next=NULL;
head2=(PNode*)malloc(sizeof(PNode)); head2->next=NULL;
head3=(PNode*)malloc(sizeof(PNode)); head3->next = NULL;
printf("请注意集合1的元素要多余集合2的元素,且元素符合集合的标准\n");
printf("请输入集合1:\n");
printflist(head1);
printf("请输入集合2:\n");
printflist(head2);
A:printf("1.交集 2.并集 3.差集 4.结束 \n ");
do
{
printf("请选择运算方式,填序号即可\n");
scanf("%d", &i);
switch (i)
{
case 1: printf("集合的交集为:");
jiaoji(head1,head2,head3);
putlist(head3);
head3->next=NULL;
break;
case 2: printf("集合的并集为:");
binji(head1,head2,head3);
putlist(head3);
head3->next = NULL;
break;
case 3:printf("集合的差集为:");
chaji(head1,head2,head3);
putlist(head3);
head3->next=NULL;
break;
case 4:break;
default:goto A;
}
}
}