日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

C语言:用链表实现集合的并和交

發(fā)布時(shí)間:2023/12/29 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C语言:用链表实现集合的并和交 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
  • 使用兩個(gè)單鏈表表示兩個(gè)集合;
  • 可鍵盤(pán)輸入集合的元素;
  • 編寫(xiě)交算法和并算法

代碼片段

建立鏈表

LinkList InitList() {//建立鏈表LinkList L, p,q;int d;L = (LinkList)malloc(sizeof(LNode));p = L;scanf("%d", &d); //輸入首個(gè)元素while (d != 0) //以0作為結(jié)束標(biāo)志{p=p->next=(LinkList)malloc(sizeof(LNode));p->data = d;scanf("%d", &d);}p->next=NULL;q=L;L=L->next;free(q); //釋放頭結(jié)點(diǎn)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; }

全部代碼

#include <stdio.h> #include <stdlib.h> #define OK 1 typedef int Status; typedef struct LNode {int data;struct LNode *next; }LNode,*LinkList;LinkList InitList() {//建立鏈表LinkList L, p,q;int d;L = (LinkList)malloc(sizeof(LNode));p = L;scanf("%d", &d);while (d != 0){p=p->next=(LinkList)malloc(sizeof(LNode));p->data = d;scanf("%d", &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("%3d",a->data);a=a->next;}return OK; }int main() {LinkList A,B,INT,UNION;printf("請(qǐng)輸入集合A的值(輸入0結(jié)束):");A = InitList();printf("請(qǐng)輸入集合B的值(輸入0結(jié)束):");B = InitList();INT=Intersection(A,B);printf("\n所求交集為:");traverselist(INT);UNION=Unionset(A,B);printf("\n所求并集為:");traverselist(UNION);return 0; }

總結(jié)

以上是生活随笔為你收集整理的C语言:用链表实现集合的并和交的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。