c语言实现线性表的应用包括集合的创建,并集,交集和输出
时间: 2023-05-18 17:04:34 浏览: 70
可以使用数组或链表来实现线性表,以下是一个使用数组实现的示例代码:
#include <stdio.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int length;
} List;
void initList(List *L) {
L->length = 0;
}
void insert(List *L, int index, int value) {
if (index < 1 || index > L->length + 1) {
printf("Error: invalid index\n");
return;
}
if (L->length >= MAXSIZE) {
printf("Error: list is full\n");
return;
}
for (int i = L->length; i >= index; i--) {
L->data[i] = L->data[i - 1];
}
L->data[index - 1] = value;
L->length++;
}
void printList(List *L) {
printf("List: ");
for (int i = 0; i < L->length; i++) {
printf("%d ", L->data[i]);
}
printf("\n");
}
void createSet(List *L) {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the elements: ");
for (int i = 0; i < n; i++) {
int value;
scanf("%d", &value);
insert(L, L->length + 1, value);
}
}
void unionSet(List *A, List *B, List *C) {
initList(C);
for (int i = 0; i < A->length; i++) {
insert(C, C->length + 1, A->data[i]);
}
for (int i = 0; i < B->length; i++) {
int value = B->data[i];
int found = 0;
for (int j = 0; j < A->length; j++) {
if (A->data[j] == value) {
found = 1;
break;
}
}
if (!found) {
insert(C, C->length + 1, value);
}
}
}
void intersectSet(List *A, List *B, List *C) {
initList(C);
for (int i = 0; i < A->length; i++) {
int value = A->data[i];
int found = 0;
for (int j = 0; j < B->length; j++) {
if (B->data[j] == value) {
found = 1;
break;
}
}
if (found) {
insert(C, C->length + 1, value);
}
}
}
int main() {
List A, B, C;
initList(&A);
initList(&B);
initList(&C);
printf("Create set A:\n");
createSet(&A);
printf("Create set B:\n");
createSet(&B);
printf("Set A: ");
printList(&A);
printf("Set B: ");
printList(&B);
unionSet(&A, &B, &C);
printf("Union of A and B: ");
printList(&C);
intersectSet(&A, &B, &C);
printf("Intersection of A and B: ");
printList(&C);
return 0;
}
对于编程类的问题,我会尽力回答,如果有不懂的地方可以继续提问。