(第三周项目3)求集合并集
来源:互联网 发布:淘宝开企业店铺的条件 编辑:程序博客网 时间:2024/05/14 20:02
假设有两个集合 A 和 B 分别用两个线性表 LA 和 LB 表示,即线性表中的数据元素即为集合中的成员。设计算法,用函数unionList(List LA, List LB, List &LC )函数实现该算法,求一个新的集合C=A∪B,即将两个集合的并集放在线性表LC中。
提示:
(1)除了实现unnionList函数外,还需要在main函数中设计代码,调用unionList进行测试和演示;
(2)可以充分利用前面建好的算法库,在程序头部直接加 #include<list.h>
即可(工程中最普遍的方法,建议采纳);
(3)也可以将实现算法中需要的线性表的基本运算对应的函数,与自己设计的所有程序放在同一个文件中。
#include <stdio.h> #include <malloc.h> //动态存储分配函数头文件 #define MaxSize 50 //必要的宏定义 typedef int ElemType; typedef struct { ElemType data[MaxSize]; int length; }SqList;ElemType e;void InitList(SqList *&L) //引用型指针 { L=(SqList *)malloc(sizeof(SqList)); //分配存放线性表的空间 L->length=0; } int LocateElem(SqList *L, ElemType e) { int i=0; while (i<L->length && L->data[i]!=e) i++; if (i>=L->length) return 0; else return i+1; } bool GetElem(SqList *L,int i,ElemType &e) { if (i<1 || i>L->length) return false; e=L->data[i-1]; return true; } void CreateList(SqList *&L,ElemType a[],int n) { int i; L=(SqList *)malloc(sizeof(SqList)); for(i=0;i<n;i++) L->data[i]=a[i]; L->length=n; } void DispList(SqList *L) { int i; for(i=0;i<L->length;i++) printf("%d",L->data[i]); printf("\n"); } void unionList(SqList *LA, SqList *LB, SqList *&LC ){int i,j;InitList(LC);//注意添加for(i=0;i<LA->length;i++)LC->data[i]=LA->data[i];for(j=0;j<LB->length;j++){if(GetElem(LB,j+1,e))if(0==LocateElem(LA,e)){LC->data[i]=LB->data[j];i++;}}LC->length=i;//注意添加}int main(){SqList *LA,*LB,*LC;int a[4]={0,9,4,8},b[6]={3,9,2,4,7,0};CreateList(LA,a,4);CreateList(LB,b,6);unionList(LA,LB,LC);DispList(LC);return 0;}
结果
总结
unionList是创建新线性表,因此需有InitList及其length。而且length比i多1。
心得
学会利用算法库。
0 0
- (第三周项目3)求集合并集
- 第三周项目(3)- 求集合并集
- 第三周--【项目 - 求集合并集】
- 第三周项目--求集合并集
- 第三周—项目3 求集合并集
- 第三周项目3求集合并集
- 第三周-项目3-求两集合并集
- 第三周项目3—求集合并集
- 第三周 项目3-求集合并集
- 第三周项目3—求集合并集
- 第三周 项目3-求集合并集
- 第三周项目3 求集合并集
- 第三周—项目3 - 求集合并集
- 第三周 项目3 - 求集合并集
- 第三周项目3-求集合并集
- 第三周项目3-求集合并集
- 第三周项目3-求集合并集
- 第三周项目3-求集合并集
- 分享七
- 第10章 并发
- js之Navigator对象
- 自定义dialog
- 正则表达式
- (第三周项目3)求集合并集
- 第3周项目4-顺序表应用问题(1)
- 通过创建帮助类,创建数据库,并在数据库中添加,修改,删除数据
- VirtIO 读书笔记
- 分享八
- 猫猫学iOS 之微博项目实战(13)发送微博调用相机里面的图片以及调用相机
- active mq集群
- HDU - 2955 Robberies(01背包)
- 笔记