资源描述:
《c语言实现的链表集合的并集与交集》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、#include#includetypedefintDatatype;//定义链表的节点typedefstructLNode{Datatypedata;LNode*next;}LNode,*LinkList;boolInitLink(LinkList&L)//初始化链表{L=(LinkList)malloc(sizeof(LNode));if(L==NULL){returnfalse;}L->next=NULL;returntrue;}boolInsertData(LinkList&L,D
2、atatypedata)//向链表中插入数据{LinkListpa=L;while(pa->next!=NULL){pa=pa->next;}LinkListp=(LinkList)malloc(sizeof(LNode));//新建数据节点if(p==NULL){printf("插入数据失败");returnfalse;}p->data=data;p->next=NULL;if(pa==NULL){pa=p;}else{pa->next=p;}returntrue;}voidcreateLink(LinkList&L){
3、printf("请输入要插入的数据,以0结束!");Datatypedata;scanf("%d",&data);while(data!=00){InsertData(L,data);scanf("%d",&data);}}voidprintLink(LinkListL)//打印链表{LinkListp=L->next;while(p!=NULL){printf("%d",p->data);p=p->next;}printf("");}boolmerger(LinkListLa,LinkListLb,LinkList&
4、Lc)//两个链表求并集,并将结果存放在Lc中{LinkListpa,pb;pb=Lb->next;//用于循环pa=La->next;while(pa!=NULL){//以La为基础链,若B中的数据在A链中不存在,则插入到Lc中InsertData(Lc,pa->data);pa=pa->next;//pos表示la链中最后一个数据节点,用于插入数据}boolflag=false;while(pb!=NULL){pa=La->next;flag=false;//用于判断B中的数据是否在A中存在while(pa!=NULL){
5、if(pa->data==pb->data){flag=false;break;//如果存在,则本次循环结束}else{flag=true;}pa=pa->next;//pa向后移动}if(flag){/*LinkListp=(LinkList)malloc(sizeof(LNode));//注释的代码是用于将A和B合并之后存放在A中if(p==NULL){printf("插入数据失败");returnfalse;}p->data=pb->data;p->next=NULL;pos->next=p;pos=p;*/Inse
6、rtData(Lc,pb->data);//将B中的数据插入到Lc中}pb=pb->next;}returntrue;}boolIntersection(LinkListLa,LinkListLb,LinkList&Lc)//两个链表求交集,结果存放在Lc中{LinkListpa,pb;pb=Lb->next;while(pb!=NULL){pa=La->next;while(pa!=NULL){if(pa->data==pb->data){//求交集时,只需找到两个链中共同的数据,插入到Lc中即可InsertData(Lc,
7、pa->data);}pa=pa->next;}pb=pb->next;}returntrue;}intmain(){LinkListLa,Lb,Lc;if(!InitLink(La)){printf("初始化链表失败");exit(1);}if(!InitLink(Lb)){printf("初始化链表失败");exit(1);}if(!InitLink(Lc)){printf("初始化链表失败");exit(1);}printf("创建第一条链表");createLink(La);printf("创建第二条链表");
8、createLink(Lb);printf("链表中的数据为");printf("La:");printLink(La);printf("Lb:");printLink(Lb);printf("链表求并集");merger(La,Lb,Lc);printf("合并之后