2.7.1
线性表的合并
[例2.1]求解一般集合的并集问题。
[问题描述]
已知两个集合A和B,现要求一个新的集合A= AUB。例如,设
A=(7, 5, 3, 11)
B=(2, 6,3)
合并后
A=(7, 5,3,11,2, 6)
[问题分析]
可以利用两个线性表LA和LB分别表示集合A和B (即线性表中的数据元素为集合中的成员),这样只需扩大线性表LA,将存在于LB中而不存在于LA中的数据元素插人到LA中去。
只要从LB中依次取得每个数据元素,并依值在LA中进行查访,若不存在,则插人之。
具体实现时既可采用顺序形式,也可采用链表形式。
算法步骤:
①分别获取LA表长m和B表长n。
②从LB中第1个数据元素开始,循环n次执行以下操作:
●从LB中查找第 i (1≤i≤n)个数据元素赋给e;
●在LA中查找元素e. 如果不存在,则将e插在表LA的最后。
#include<iostream>
#include<fstream>
using namespace std;
#define MAXSIZE 100
#define ERROR 0
typedef struct { //定义顺序表
int *elem;
int length;
} List;
int n, m;
char st = 'A';
void InitList(List &L) //创建顺序表
{
L.elem = new int[MAXSIZE];
L.length = 0;
}
void ListInput(List &L, int n) //顺序表数据的输入
{
int i = 0;
char filename[20] = { 0 };
cout << "请输入顺序表L" << st << "的数据文件名称(文件名+“.txt”,如List" << st << ".txt):" << endl;
++st;
gets(filename);
fstream file;
file.open(filename);
if (!file) {
cout << "未找到相关文件,无法打开!" << endl;
exit(ERROR);
}
while (!file.eof()) {
file >> L.elem[i];
i++;
}
L.length = i;
}
int ListLength(List L) //求顺序表的长度
{
return L.length;
}
void GetElem(List L, int i, int &e) //求顺序表的第i个元素,并以e返回
{
e = L.elem[i - 1];
}
bool LocateElem(List L, int e) //判断List里有没有e这个元素
{
int i;
for (i = 0; i < L.length; i++)
if (e == L.elem[i])
return true;
return false;
}
void ListInsert(List &L, int e) //将e插入到List的最后
{
L.elem[L.length] = e;
L.length++;
}
void ListOutput(List L) //输出List
{
int i;
for (i = 0; i < L.length; i++)
cout << L.elem[i] << " ";
cout << endl;
}
void unionList(List &LA, List LB) // 线性表的合并(顺序表)
{
//将所有在线性表LB中但不在LA中的数据元素插入到LA中
int LA_len, LB_len, i, e;
LA_len = ListLength(LA);
LB_len = ListLength(LB); //求线性表的长度
for (i = 1; i <= LB_len; i++) {
GetElem(LB, i, e); //取LB中第i个数据元素赋给e
if (!LocateElem(LA, e)) //LA中不存在和e相同的数据元素,则插入之
ListInsert(LA, e);
}
} //unionList
int main() {
List LA, LB;
InitList(LA);
InitList(LB);
ListInput(LA, n);
ListInput(LB, m);
unionList(LA, LB);
cout << "LA和LB合并后的集合为:\n";
ListOutput(LA);
return 0;
}
上述算法的时间复杂度取决于抽象数据类型List定义中基本操作的执行时间,假设LA和LB的表长分别为m和n,循环执行n次,则:当采用顺序存储结构时,在每次循环中,GetElem 和ListInsert这两个操作的执行时间和表长无关,LocateElem 的执行时间和表长m成正比,因此,算法的时间复杂度为O(m * n)。