第三周 项目3 求集合并集

来源:互联网 发布:java还能火几年 编辑:程序博客网 时间:2024/05/22 17:47

 假设有两个集合 A 和 B 分别用两个线性表 LA 和 LB 表示,即线性表中的数据元素即为集合中的成员。设计算法,用函数unionList(List LA, List LB, List &LC )函数实现该算法,求一个新的集合C=A∪B,即将两个集合的并集放在线性表LC中。

提示: 
(1)除了实现unnionList函数外,还需要在main函数中设计代码,调用unionList进行测试和演示; 
(2)可以充分利用前面建好的算法库[点击…],在程序头部直接加 #include<list.h>即可(工程中最普遍的方法,建议采纳); 
(3)也可以将实现算法中需要的线性表的基本运算对应的函数,与自己设计的所有程序放在同一个文件中。

[cpp] view plain copy
  1. #include "list.h"  
  2. #include <stdio.h>  
  3.   
  4. void unionList(SqList *LA, SqList *LB, SqList *&LC)  
  5. {  
  6.     int lena,i;  
  7.     ElemType e;  
  8.     InitList(LC);  
  9.     for (i=1; i<=ListLength(LA); i++) //将LA的所有元素插入到Lc中  
  10.     {  
  11.         GetElem(LA,i,e);  
  12.         ListInsert(LC,i,e);  
  13.     }  
  14.     lena=ListLength(LA);         //求线性表LA的长度  
  15.     for (i=1; i<=ListLength(LB); i++)  
  16.     {  
  17.         GetElem(LB,i,e);         //取LB中第i个数据元素赋给e  
  18.         if (!LocateElem(LA,e)) //LA中不存在和e相同者,插入到LC中  
  19.             ListInsert(LC,++lena,e);  
  20.     }  
  21. }  
  22.   
  23. //用main写测试代码  
  24. int main()  
  25. {  
  26.     SqList *sq_a, *sq_b, *sq_c;  
  27.     ElemType a[6]= {5,8,7,2,4,9};  
  28.     CreateList(sq_a, a, 6);  
  29.     printf("LA: ");  
  30.     DispList(sq_a);  
  31.   
  32.     ElemType b[6]= {2,3,8,6,0};  
  33.     CreateList(sq_b, b, 5);  
  34.     printf("LB: ");  
  35.     DispList(sq_b);  
  36.     unionList(sq_a, sq_b, sq_c);  
  37.     printf("LC: ");  
  38.     DispList(sq_c);  
  39.     return 0;  
  40. }  

原创粉丝点击