#include <stdio.h>
#include <stdlib.h>
#define OK 1
typedef int Status;
typedef struct LNode
{
char data;
struct LNode *next;
}LNode,*LinkList;
LinkList InitList()
{//建立链表
LinkList L, p,q;
char d;
L = (LinkList)malloc(sizeof(LNode));
p = L;
scanf("%c", &d);
while (d != '#')
{
p=p->next=(LinkList)malloc(sizeof(LNode));
p->data = d;
scanf("%c", &d);
}
p->next=NULL;
q=L;
L=L->next;
free(q);
return L;
}
LinkList Intersection(LinkList a, LinkList b)
{//求交集
LinkList LA, LB,q;
LA =(LinkList)malloc(sizeof(LNode));
LB = LA;
while (a!=NULL)
{
q=b;
while (q!=NULL)
{
if (q->data == a->data)
{
LB=LB->next=(LinkList)malloc(sizeof(LNode));
LB->data = a->data;
break;
}
q = q->next;
}
a = a->next;
}
LB->next=NULL;
LinkList p;
p = LA;
LA = LA->next;
free(p);
return LA;
}
LinkList Unionset(LinkList a, LinkList b)
{//求并集
LinkList L,q;
L=b;
while (a!=NULL)
{
while (b)
{
q=b;
if(a->data==b->data)
break;
b=b->next;
}
if(b==NULL)
{
q=q->next=(LinkList)malloc(sizeof(LNode));
q->data=a->data;
q->next=NULL;
}
b=L;
a=a->next;
}
return L;
}
Status traverselist(LinkList a)
{//遍历链表
while(a!=NULL)
{
printf("%3c",a->data);
a=a->next;
}
return OK;
}
int main()
{
LinkList A,B,INT,UNION;
printf("请输入集合A的值(输入#结束):");
A = InitList();
printf("请输入集合B的值(输入#结束):");
B = InitList();
INT=Intersection(A,B);
printf("\n所求交集为:");
traverselist(INT);
UNION=Unionset(A,B);
printf("\n所求并集为:");
traverselist(UNION);
return 0;
}