第3周项目3-求集合并集

    xiaoxiao2023-02-02  14

    问题及代码:

    /* * Copyright(c) 2016, 烟台大学计算机与控制工程学院 * All rights reserved. * 文件名称: * 作 者:路亚丽 * 完成日期:2016年 9月 17日 * 版 本 号:v1.0 * * 问题描述: 假设有两个集合 A 和 B 分别用两个线性表 LA 和 LB 表示,即线性表中的数据元素即为集合中的成员。 设计算法,用函数unionList(List LA, List LB, List &LC )函数实现该算法,求一个新的集合C=A∪B,即将两个集合的并集放在线性表LC中。    * 输入描述:LA,LB * 程序输出:LC */ #include "list.h" #include <stdio.h> void unionList(SqList *LA, SqList *LB, SqList *&LC) { int lena,i; ElemType e; InitList(LC); for (i=1; i<=ListLength(LA); i++) //将LA的所有元素插入到Lc中 { GetElem(LA,i,e); ListInsert(LC,i,e); } lena=ListLength(LA); //求线性表LA的长度 for (i=1; i<=ListLength(LB); i++) { GetElem(LB,i,e); //取LB中第i个数据元素赋给e if (!LocateElem(LA,e)) //LA中不存在和e相同者,插入到LC中 ListInsert(LC,++lena,e); } } //用main写测试代码 int main() { SqList *sq_a, *sq_b, *sq_c; ElemType a[6]= {1,2,3,4}; CreateList(sq_a, a, 4); printf("LA: "); DispList(sq_a); ElemType b[6]= {5,6,7,8}; CreateList(sq_b, b, 4); printf("LB: "); DispList(sq_b); unionList(sq_a, sq_b, sq_c); printf("LC: "); DispList(sq_c); return 0; }

    运行结果:

    知识点总结:

    顺序表的合并

    学习心得:

    多文件的形式似的程序更加简洁,所以应该经常积累算法库。

    转载请注明原文地址: https://ju.6miu.com/read-1138600.html
    最新回复(0)