线性表的合并
[例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的最后。
————————————————
版权声明:本文为CSDN博主「时间sk」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_63215361/article/details/131401471
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
#define ERROR 0
typedef struct LNode {
int data; //结点的数据域
struct LNode *next; //结点的指针域
} LNode, *List; //LinkList为指向结构体LNode的指针类型
int n, m;
char st = 'A';
void InitList(List &L) //创建链表
{
L = new LNode;
L->next = NULL;
}
void ListInput(List &L, int n) //链表数据的输入
{
int i;
List p, r;
r = L;
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()) {
p = new LNode;
file >> p->data;
p->next = NULL;
r->next = p;
r = p;
n++;
}
file.close();
}
bool LocateElem(List L, int e) //判断List里有没有e这个元素
{
List p;
p = L->next;
while (p != NULL) {
if (p->data == e)
return true;
p = p->next;
}
return false;
}
void ListInsert(List &L, int e) //将e插入到List中
{
List p;
p = new LNode;
p->data = e;
p->next = L->next;
L->next = p;
}
void ListOutput(List L) //输出List
{
List p;
p = L->next;
while (p != NULL) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void unionList(List &LA, List LB) // 线性表的合并(链表)
{
//将所有在线性表LB中但不在LA中的数据元素插入到LA中
int e;
List p;
p = LB->next;
while (p != NULL) {
e = p->data;
if (!LocateElem(LA, e)) //LA中不存在和e相同的数据元素,则插入之
ListInsert(LA, e);
p = p->next;
}
} //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;
}