问题及代码:
- /*
- Copyright (c)2016,烟台大学计算机与控制工程学院
- All rights reserved.
- 文件名称:ww.cpp
- 作 者:武昊
- 完成日期:2016年9月18日
- 版 本 号:v1.0
- 问题描述:假设有两个集合 A 和 B 分别用两个线性表 LA 和 LB 表示,即线性表中的数据元素即为集合中的成员。设计算法,用函数unionList(List LA, List LB, List &LC )函数实现该算法,求一个新的集合C=A∪B,即将两个集合的并集放在线性表LC中。
- 输入描述:无
- 程序输出:数据。
- */
- #include<stdio.h>
- #include<malloc.h>
- #define MAXSize 50
- typedef struct
- {
- int data[MAXSize]; //存放顺序表中元素
- int length; //存放顺序表的长度
- }sqlist; //顺序表的类型定义
- void creatlist(sqlist *&,int a[],int );
- void DispList(sqlist *);
- void unionlist(sqlist *,sqlist *,sqlist *&);
- int main()
- {
- sqlist *sqa,*sqb,*sqc;
- int a[6]= {5,8,7,2,4,9};
- creatlist(sqa,a,6);
- printf("LA:");
- DispList(sqa);
- int b[6]= {2,3,8,6,0};
- creatlist(sqb,b,6);
- printf("LB:");
- DispList(sqb);
- unionlist(sqa,sqb,sqc);
- printf("LC:");
- DispList(sqc);
- return 0;
- }
- void creatlist(sqlist *&l,int 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 *a,sqlist *b,sqlist *&c)
- {
- c=(sqlist *)malloc(sizeof(sqlist));
- int i,j=0,k=0,l=0;
- c->length=0;
- for(i=0;i<a->length;i++)
- {
- c->data[i]=a->data[i];
- c->length++;
- }
- while(j<b->length)
- {
- while(b->data[j]!=a->data[k]&&k<b->length)
- {
- k++;
- }
- if(k==b->length)
- {
- c->data[i]=b->data[j];
- i++;
- c->length++;
- }
- k=0;
- j++;
- }
- }
运行结果:
学习心得:
求集合并集是算法一部分,熟练掌握后有利于我们算法库的应用。