要求:限定范圍為【'a',……'z'】,以有序鏈表表示集合
c-free通過
code:
code#include
#include
typedef struct pointer{
char dat;
struct pointer *next;
} pointer;
void readdata(pointer *head){ //讀集合
pointer *p;
char tmp;
printf("input data (以'0'結束):");
scanf("%c",&tmp);
while(tmp!='0')
{
p=(pointer *)malloc(sizeof(struct pointer));
p->dat=tmp;
p->next=head->next;
head->next=p;
scanf("%c",&tmp);
}
}
void disp(pointer *head){ //顯示集合數據
pointer *p;
p=head->next;
while(p!=NULL)
{
printf("%c ",p->dat);
p=p->next;
}
printf("\n");
}
void bing(pointer *head1,pointer *head2, pointer *head3){ //計算集合1與集合2的並
pointer *p1,*p2,*p3;
p1=head1->next;
while(p1!=NULL)
{
p3=(pointer *)malloc(sizeof(struct pointer));
p3->dat=p1->dat;
p3->next=head3->next;
head3->next=p3;
p1=p1->next;
}
p2=head2->next;
while(p2!=NULL)
{
p1=head1->next;
while((p1!=NULL)&&(p1->dat!=p2->dat))
p1=p1->next;
if(p1==NULL)
{
p3=(pointer *)malloc(sizeof(struct pointer));
p3->dat=p2->dat;
p3->next=head3->next;
head3->next=p3;
}
p2=p2->next;
}
}
void jiao(pointer *head1,pointer *head2, pointer *head3){ //計算集合1與集合2的交
pointer *p1,*p2,*p3;
p1=head1->next;
while(p1!=NULL)
{
p2=head2->next;
while((p2!=NULL)&&(p2->dat!=p1->dat))
p2=p2->next;
if((p2!=NULL)&&(p2->dat=p1->dat))
{
p3=(pointer *)malloc(sizeof(struct pointer));
p3->dat=p1->dat;
p3->next=head3->next;
head3->next=p3;
}
p1=p1->next;
}
}
void cha(pointer *head1,pointer *head2, pointer *head3){ //計算集合1與集合2的差
pointer *p1,*p2,*p3;
p1=head1->next;
while(p1!=NULL)
{
p2=head2->next;
while((p2!=NULL)&&(p2->dat!=p1->dat))
p2=p2->next;
if(p2==NULL)
{
p3=(pointer *)malloc(sizeof(struct pointer));
p3->dat=p1->dat;
p3->next=head3->next;
head3->next=p3;
}
p1=p1->next;
}
}
int main(){
pointer *head1,*head2,*head3;
head1=(pointer *)malloc(sizeof(struct pointer));
head1->next=NULL;
head2=(pointer *)malloc(sizeof(struct pointer));
head2->next=NULL;
head3=(pointer *)malloc(sizeof(struct pointer));
head3->next=NULL;
printf("輸入集合1:\n");
readdata(head1);
printf("輸入集合2:\n");
readdata(head2);
printf("集合1為:\n");
disp(head1);
printf("集合2為:\n");
disp(head2);
printf("集合1與集合2的並為:\n");
bing(head1,head2,head3);
disp(head3);
head3->next=NULL;
printf("集合1與集合2的交為:\n");
jiao(head1,head2,head3);
disp(head3);
head3->next=NULL;
printf("集合1與集合2的差為:\n");
cha(head1,head2,head3);
disp(head3);
}