问题及代码:
/*
*Copyright (c) 2014,烟台大学计算机学院
*All rights reserved.
*文件名称:求集合并集
*作者:李子伦
*完成日期:2015年9月21日
*
*问题描述: 假设有两个集合 A 和 B 分别用两个线性表 LA 和 LB 表示,即线性表中的数据元素即为集合中的成员。
设计算法,用函数unionList(List LA, List LB, List &LC )函数实现该算法,求一个新的集合C=A∪B,即将两个集合的并集放在线性表LC中
*输入描述:数组a,b
*程序输出:测试结果
*/
(1)1.h
#ifndef LIST_H_INCLUDED
#define LIST_H_INCLUDED
#include<stdio.h>
#include<malloc.h>
#define MaxSize 50 //Maxsize将用于后面定义存储空间的大小
typedef int ElemType; ElemType在不同场合可以根据问题的需要确定,在此取简单的int
typedef struct
{
ElemType data[MaxSize];
int length;
} SqList;
void CreateList(SqList *&L, ElemType a[], int n);
void DispList(SqList *L);
bool ListEmpty(SqList *L);
int ListLength(SqList *L);
int LocateElem(SqList *L, ElemType e);
bool GetElem(SqList *L,int i,ElemType &e);
void DestroyList(SqList *&L);
void InitList(SqList *&L);
bool ListInsert(SqList *&L, int i, ElemType e);
void unionList(SqList *LA, SqList *LB, SqList *&LC);
#endif
(2)main.cpp
#include<stdio.h>
#include"1.h"
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[10]= {2,5,77,1,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;
}
(2)void.cpp
#include"1.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);
}
}
void DispList(SqList *L) //输出线性表
{
int i;
if (ListEmpty(L))
return;
for(i=0; i<L->length; i++)
printf("%d ",L->data[i]);
printf("\n");
}
bool ListEmpty(SqList *L) //判断链表是否存在
{
return(L->length==0);
}
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;
}
int ListLength(SqList *L) //求线性表长度
{
return(L->length);
}
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 DestroyList(SqList *&L) //销毁线性表
{
free(L);
}
bool ListInsert(SqList *&L, int i, ElemType e) //插入线性表
{
int j;
if(i<1 || i>L->length+1)
return false;
i--;
for(j=L->length;j>i;j--) //将date[i]及后面的元素后移一个位置
L->data[j]=L->data[j-1];
L->data[i]=e;
L->length++;
return true;
}
void InitList(SqList *&L) //初始化线性表
{
L=(SqList *)malloc(sizeof(SqList));
L->length=0;
}
运行结果:
知识点总结:
在求集合并集的过程中,主要用到的还是顺序表的基本运算算法,在构建unionList函数时应当注意对顺序表是否为空表的判断。
心得体会:
应当树立工程思维,切记不要把代码放在一个文件中。