C语言:用链表实现集合的并和交
生活随笔
收集整理的這篇文章主要介紹了
C语言:用链表实现集合的并和交
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
- 使用兩個(gè)單鏈表表示兩個(gè)集合;
- 可鍵盤輸入集合的元素;
- 編寫交算法和并算法
代碼片段
建立鏈表
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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 任我行在线安装方式
- 下一篇: SMB小传 —— SMB网络文件系统协议