用线性表顺序存储结构实现一个算法求A和B俩个集合的并集,用C语言写全部代码
时间: 2024-03-11 08:47:25 浏览: 29
以下是使用线性表顺序存储结构实现求A和B两个集合的并集的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100 // 线性表最大长度
typedef struct {
int data[MAXSIZE];
int length;
} SqList;
void InitList(SqList *L) { // 初始化线性表
L->length = 0;
}
int ListInsert(SqList *L, int elem) { // 在线性表末尾插入元素
if (L->length == MAXSIZE) { // 线性表已满
return 0;
}
L->data[L->length] = elem;
L->length++;
return 1;
}
void Union(SqList A, SqList B, SqList *C) { // 求A和B的并集
InitList(C); // 初始化线性表C
int i, j;
for (i = 0; i < A.length; i++) { // 将A中的元素插入C中
ListInsert(C, A.data[i]);
}
for (j = 0; j < B.length; j++) { // 将B中的元素插入C中
int flag = 0; // 标记B中的元素是否已经在C中
for (i = 0; i < A.length; i++) {
if (B.data[j] == A.data[i]) {
flag = 1;
break;
}
}
if (!flag) {
ListInsert(C, B.data[j]);
}
}
}
int main() {
SqList A, B, C;
InitList(&A);
InitList(&B);
ListInsert(&A, 1);
ListInsert(&A, 2);
ListInsert(&A, 3);
ListInsert(&B, 2);
ListInsert(&B, 3);
ListInsert(&B, 4);
Union(A, B, &C);
int i;
for (i = 0; i < C.length; i++) {
printf("%d ", C.data[i]);
}
printf("\n");
return 0;
}
```
以上代码中,`SqList`结构体表示线性表,包含一个`data`数组和一个`length`成员变量。`InitList`函数用于初始化线性表,将线性表的`length`设为0。`ListInsert`函数用于在线性表末尾插入元素。`Union`函数用于求A和B的并集,其中用到了`ListInsert`函数。`main`函数用于测试求并集的函数。