请设计一个算法,,求A和B两个单链表表示的集合的交集、并集、差集_百度...
发布网友
发布时间:2024-10-23 15:27
我来回答
共1个回答
热心网友
时间:2024-11-13 22:35
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{char data; /*定义了数据域,这里存储的是char类型*/
struct Node*next; /*定义了指针域*/
}*linklist;
void readdata(linklist head)
{ linklist p;
char a;
scanf("%c",&a);
while(a!='\n')
{ p=(linklist)malloc(sizeof(structNode));
p->data=a;
p->next=head->next;
head->next=p;
scanf("%c",&a);
}
}
void pop(linklist head)
{ linklist p;
p=head->next;
while(p!=NULL)
{ printf("%c",p->data);
p=p->next;
}
printf("\n");
}
/******求两个链表的并集******/
void bingji(linklist head1,linklisthead2,linklist head3)
{ linklist p1,p2,p3;
p1=head1->next;
while(p1!=NULL)
{ p2=head2->next;
while((p2!=NULL)&&(p2->data!=p1->data))
p2=p2->next;
if((p2!=NULL)&&(p2->data==p1->data))
{ p3=(linklist)malloc(sizeof(struct Node));
p3->data=p1->data;
p3->next=head3->next;
head3->next=p3; }
p1=p1->next; } }
/********求两个链表的交集********/
void jiaoji(linklist head1,linklisthead2,linklist head3)
{ linklist p1,p2,p3;
p1=head1->next;
while(p1!=NULL)
{ p3=(linklist)malloc(sizeof(struct Node));
p3->data=p1->data;
p3->next=head3->next;
head3->next=p3;
p1=p1->next; }
p2=head2->next;
while(p2!=NULL)
{ p1=head1->next;
while((p1!=NULL)&&(p1->data!=p2->data))
p1=p1->next;
if (p1==NULL)
{ p3=(linklist)malloc(sizeof(struct Node));
p3->data=p2->data;
p3->next=head3->next;
head3->next=p3; }
p2=p2->next;
}
}
/********求两个链表的差集************/
void chaji(linklist head1,linklisthead2,linklist head3)
{ linklist p1,p2,p3;
p1=head1->next;
while(p1!=NULL) //循环语句执行链表的差集运算
{ p2=head2->next;
while((p2!=NULL)&&(p2->data!=p1->data))
p2=p2->next;
if(p2==NULL)
{ p3=(linklist)malloc(sizeof(struct Node));
p3->data=p1->data;
p3->next=head3->next;
head3->next=p3;
}
p1=p1->next;
}
}
void main(linklist head1,linklisthead2,linklist head3)
{
int x;
printf("input values and end up with ‘enter’ \n");
head1=(linklist)malloc(sizeof(struct Node)); /*为结点分配内存空间*/
head1->next=NULL;
head2=(linklist)malloc(sizeof(struct Node));
head2->next=NULL;
head3=(linklist)malloc(sizeof(struct Node));
head3->next=NULL;
printf("please input ji he 1 \n");
readdata(head1);
printf("please input ji he 2 \n"); //调用链表输出函数链表数据
readdata(head2);
A:printf("1.bing ji 2.jiaoji 3.cha ji 4.exit \n");
do{
printf("qing xuan ze xu hao\n");
scanf("%d",&x);
switch(x)
{
case 1:
printf("liang ge ji he debing ji shi \n");
jiaoji(head1,head2,head3);
pop(head3);
head3->next=NULL;
break;
case 2:
printf("liang ge ji he dejiao ji shi \n");
bingji(head1,head2,head3);
pop(head3);
head3->next=NULL;
break;
case 3:
printf("liang ge ji he decha ji shi \n");
chaji(head1,head2,head3);
pop(head3);
head3->next=NULL;
break;
case 4: break;
default:goto A; }
}
while(x!=4);
}