#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node*next;
};
typedef struct node NODE;
//主函数
int main()
{
NODE *head1,*head2,*head3;//定义头结点
void creatlink1();//创建链表存放A
void creatlink2();//存放B
void intersectionsetd();//求并集
void print(); //此处调用求并集函数
//输出并集函数
head1 = (NODE*)malloc(sizeof(NODE));//申请头结点
head2 = (NODE*)malloc(sizeof(NODE));
head3 = (NODE*)malloc(sizeof(NODE));
printf("请输入数组A中各值:\n");
creatlink1(head1);
printf("请输入数组B中各值:\n");
creatlink2(head2);
intersectionsetd(head1, head2,head3);//调用并集函数
printf("他们的并集是:\n");
print(head3);//输出并集 print(head4)
return 0;
}
//创建单链表存放A
void creatlink1(NODE *head1)
{
NODE *m ,*n;
int num1;
m=head1;
do
{
scanf("%d",&num1);
n=(NODE*)malloc(sizeof(NODE));
n->data=num1;
m ->next=n;
m =n;
} while(getchar()!='\n');
m ->next=NULL;
}
//创建单链表存放B
void creatlink2(NODE *head2)
{
NODE *k ,*t ;
int num2;
k=head2;
do
{
scanf("%d",&num2);
t=(NODE*)malloc(sizeof(NODE));
t->data=num2;
k->next=t;
k=t;
}while(getchar()!='\n');
k->next=NULL;
}
//求并集函数
void intersectionsetd(NODE *A,NODE *B,NODE *D)
{
NODE*rr,*p,*q,*ss; //pq不用变,指向D 中间
rr=D;
p=A ->next;
q=B ->next;
while((p!=NULL)||(q!=NULL))
{
/*4种情况,
A为空,B为空;
A空B不空 D=B;
A不空B空 D=A;
A,B都不为空求交集;*/
ss=(NODE*)malloc(sizeof(NODE));
if((p==NULL)&&(q==NULL))
//输出AB都为空,交集为空
{
//ss=(NODE*)malloc(sizeof(NODE));
rr=NULL;
printf("A和B都为空,并集D为空\n");
}
else if((p==NULL)&&(q!=NULL))
//把q的书存入D中输出
{
//ss=(NODE*)malloc(sizeof(NODE));
ss->data=q->data;
rr->next=ss;
rr=ss;
q=q->next;
}
else if((p!=NULL)&&(q==NULL))
//把p的数存入D中输出
{
//ss=(NODE*)malloc(sizeof(NODE));
ss->data=p->data;
rr->next=ss;
rr=ss;
p=p->next;
}
else if((p!=NULL)&&(q!=NULL))
//比较求并
{
//ss=(NODE*)malloc(sizeof(NODE));
if(p->data>q->data)//a大于b
{
ss->data=q->data;
rr->next=ss;
rr=ss;
q=q->next;
}
else if(p->data<q->data) //a<b
{
ss->data=p->data;
rr->next=ss;
rr=ss;
p=p->next;
}
else if(p->data==q->data)//a=b
{
ss->data=q->data;
rr->next=ss;
rr=ss;
p=p->next;
q=q->next;
}
}
}
rr->next=NULL;
}
//并集输出函数
void print(NODE*head3)
{
NODE*kk;
kk=head3->next;
if(kk!=NULL)
do
{
printf("%d ",kk->data);
kk=kk->next;
}while(kk!=NULL);
}
/*
转载请说明原文出处
*/