线性表求与运算
题目描述:
假设利用两个线性表LA和LB分别表示集合A和B(即线性表中的数据元素即为集合中的成员),现要求一个新的集合A=AUB
解题思路:
扩大线性表LA,将存在于线性表LB中而不存在线性表LA中的数据元素插入到线性表LA中去。只要从线性表LB中依次取得每个数据元素,并依值在线性表LA中访问,若不存在则插入之。
使用顺序表实现的代码如下:
#include<iostream> using namespace std; struct SqList { int *data; //存储空间基地址 int length; //当前长度 int listsize; //当前分配的存储容量 }; void Show(SqList *L) { for(int i=0;i<L->length;i++)cout<<L->data[i]<<" "; cout<<endl; } bool Locate(SqList *L,int x) { for(int i=0;i<L->length;i++) { if(L->data[i]==x)return true; } return false; } void Insert(SqList *L,int x) { int len = L->length; L->data[len] = x; if(L->length+1<=L->listsize)L->length++; } //核心函数 void Union(SqList *LA,SqList *LB) { int lb_len = LB->length; for(int i=0;i<lb_len;i++) { if(!Locate(LA,LB->data[i])) { Insert(LA,LB->data[i]); } } } int main() { int a[20]={1,2,3,4,5,6,7,8,9,10}; int b[7]={1,2,12,34,7,56,22}; SqList LA,LB; LA.data = a; LA.length = 10; LA.listsize = 20; LB.data = b; LB.length = 7; LB.listsize = 7; cout<<"LA: "; Show(&LA); cout<<"LB: "; Show(&LB); Union(&LA,&LB); cout<<"Union: "; Show(&LA); return 0; }核心代码为Union函数。
运行结果为:
LA: 1 2 3 4 5 6 7 8 9 10
LB: 1 2 12 34 7 56 22
Union: 1 2 3 4 5 6 7 8 9 10 12 34 56 22