问题及代码:
/* *Copyright(c) 2015, 烟台大学计算机学院 *All rights reserved. *文件名称:求集合并集.cpp *作 者:杜文文 *完成日期:2015年 10月 5日 *问题描述:假设有两个集合 A 和 B 分别用两个线性表 LA 和 LB 表示, 即线性表中的数据元素即为集合中的成员。 设计算法,用函数unionList(List LA, List LB, List &LC )函数实现该算法, 求一个新的集合C=A∪B,即将两个集合的并集放在线性表LC中。 *输入描述:若干数据 *程序输出:LA的集合数据、LB的集合数据、LC的集合数据 */
list.h:
#ifndef LIST_H_INCLUDED #define LIST_H_INCLUDED #define MaxSize 50 typedef int ElemType; typedef struct { ElemType data[MaxSize]; int length; } SqList; void CreateList(SqList *&L, ElemType a[], int n);//用数组创建线性表 void InitList(SqList *&L);//初始化线性表InitList(L) void DestroyList(SqList *&L);//销毁线性表DestroyList(L) bool ListEmpty(SqList *L);//判定是否为空表ListEmpty(L) int ListLength(SqList *L);//求线性表的长度ListLength(L) void DispList(SqList *L);//输出线性表DispList(L) bool GetElem(SqList *L,int i,ElemType &e);//求某个数据元素值GetElem(L,i,e) int LocateElem(SqList *L, ElemType e);//按元素值查找LocateElem(L,e) bool ListInsert(SqList *&L,int i,ElemType e);//插入数据元素ListInsert(L,i,e) bool ListDelete(SqList *&L,int i,ElemType &e);//删除数据元素ListDelete(L,i,e)#endif // LIST_H_INCLUDED #endif
main.cpp:
#include "list.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[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; }
list.cpp:
#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); } } void DispList(SqList *L) { int i; if (ListEmpty(L)) return; for (i=0; i<L->length; i++) printf("%d ",L->data[i]); printf("\n"); } 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; }
运行结果:
知识点总结:
通过这个程序我才真正认识到在编译代码的时候建立工程是多么的重要,而且头文件一定在源文件中再声明一次,最重要的是看清主函数中到底包含几个函数,一定在源文件中写全。
学习心得:
时隔好久才发了一篇博客,至今都第六周了,不知道该说啥,快写博客吧