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

来源:互联网 发布:java 得到tomcat路径 编辑:程序博客网 时间:2024/05/14 17:12
/*  * Copyright (c).2014, 烟台大学计算机学院  * All rights reserved.  *文件名称:test.cpp  *作    者:董子宾  *完成日期:2015年 9 月 21日  *版 本 号:v1.0  *  *问题描述:假设有两个集合A和B分别用两个线性表LA和LB表示,即线性表中的数据元素即为集合中的成员。设计算法,用函数unionList(List LA, List LB, List &LC )函数实现该算法,求一个新的集合C=A∪B,即将两个集合的并集放在线性表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]= {5,8,7,2,4,9};    CreateList(sq_a, a, 6);    printf("LA: ");    DispList(sq_a);    ElemType b[6]= {2,3,8,6,0};    CreateList(sq_b, b, 5);    printf("LB: ");    DispList(sq_b);    unionList(sq_a, sq_b, sq_c);    printf("LC: ");    DispList(sq_c);    return 0;}


运行结果:

 

知识点总结:可以充分利用前面建好的算法库,在程序头部直接加 #include<list.h>即可

 

心得体会:把复杂的程序分层看不但清晰易懂,而且容易找错误。建立算法库可以更简单的写程序

 

 

0 0
原创粉丝点击