用C语言编写一个程序,采用顺序表表示集合(假设同一个集合中不存在重复的元素),将其按递增的方式排序,并求这样的两个集合的并,交,差。(并,交,差分开编写采用函数调用,设计一个菜单 输入1求并集,输入2求交集,输入3求差集)
时间: 2024-03-15 19:44:04 浏览: 28
好的,以下是代码实现:
```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;
}
void Insert(SqList *L, int x) {
if (L->length == MAXSIZE) {
printf("List is full.\n");
return;
}
L->data[L->length++] = x;
}
void Sort(SqList *L) {
int i, j, temp;
for (i = 0; i < L->length - 1; i++) {
for (j = i + 1; j < L->length; j++) {
if (L->data[i] > L->data[j]) {
temp = L->data[i];
L->data[i] = L->data[j];
L->data[j] = temp;
}
}
}
}
void PrintList(SqList *L) {
int i;
for (i = 0; i < L->length; i++) {
printf("%d ", L->data[i]);
}
printf("\n");
}
void Union(SqList *A, SqList *B, SqList *C) {
int i, j, k;
i = j = k = 0;
while (i < A->length && j < B->length) {
if (A->data[i] < B->data[j]) {
C->data[k++] = A->data[i++];
} else if (A->data[i] > B->data[j]) {
C->data[k++] = B->data[j++];
} else {
C->data[k++] = A->data[i++];
j++;
}
}
while (i < A->length) {
C->data[k++] = A->data[i++];
}
while (j < B->length) {
C->data[k++] = B->data[j++];
}
C->length = k;
}
void Intersection(SqList *A, SqList *B, SqList *C) {
int i, j, k;
i = j = k = 0;
while (i < A->length && j < B->length) {
if (A->data[i] < B->data[j]) {
i++;
} else if (A->data[i] > B->data[j]) {
j++;
} else {
C->data[k++] = A->data[i++];
j++;
}
}
C->length = k;
}
void Difference(SqList *A, SqList *B, SqList *C) {
int i, j, k;
i = j = k = 0;
while (i < A->length && j < B->length) {
if (A->data[i] < B->data[j]) {
C->data[k++] = A->data[i++];
} else if (A->data[i] > B->data[j]) {
j++;
} else {
i++;
j++;
}
}
while (i < A->length) {
C->data[k++] = A->data[i++];
}
C->length = k;
}
void Menu() {
printf("1. Union\n");
printf("2. Intersection\n");
printf("3. Difference\n");
printf("Please enter your choice (1/2/3): ");
}
int main() {
SqList A, B, C;
int i, x, choice;
InitList(&A);
InitList(&B);
InitList(&C);
printf("Enter set A (separated by spaces, end with -1): ");
while (scanf("%d", &x) && x != -1) {
Insert(&A, x);
}
printf("Enter set B (separated by spaces, end with -1): ");
while (scanf("%d", &x) && x != -1) {
Insert(&B, x);
}
Sort(&A);
Sort(&B);
Menu();
scanf("%d", &choice);
switch (choice) {
case 1:
Union(&A, &B, &C);
printf("A union B: ");
PrintList(&C);
break;
case 2:
Intersection(&A, &B, &C);
printf("A intersection B: ");
PrintList(&C);
break;
case 3:
Difference(&A, &B, &C);
printf("A difference B: ");
PrintList(&C);
break;
default:
printf("Invalid choice.\n");
break;
}
return 0;
}
```
注:此处的 `SqList` 采用顺序表实现。
阅读全文