题目:通过键盘,分别输入两个数据元素类型为正整数的聚集A和B,以负数输入为竣事条件,输出两个聚集的交、并、差。从程序完善性上思量,聚集元素输入时,要有查抄元素重复的功能。聚集可以用数组也可以用链表存储。
样例:
聚集的交、并差
输入: A={1,2,3,4,5} B={3,4,5,6,7}
输出 A交B={3, 4, 5} A并B={1,2,3,4,5,6,7} A-B={1, 2}
- #include <stdio.h>
- #include <stdlib.h>
- void input(int** arr, int* size, int* capacity) {
- int num;
- while (scanf("%d", &num) == 1 && num >= 0) {
- int exists = 0;
- for (int i = 0; i < *size; ++i) {
- if ((*arr)[i] == num) {
- exists = 1;
- break;
- }
- }
- if (exists) continue;
- // 对数组进行扩容
- if (*size >= *capacity) {
- int newCapacity = *capacity * 2;
- int* newArr = (int*)realloc(*arr, newCapacity * sizeof(int));
- *arr = newArr;
- *capacity = newCapacity;
- }
- (*arr)[(*size)++] = num;
- }
- // 清除输入缓冲区
- while (getchar() != '\n');
- }
- int main() {
- // 初始化集合A
- int capacityA = 2;
- int* A = (int*)malloc(capacityA * sizeof(int));
- if (A == NULL) {
- printf("Memory allocation failed.\n");
- return 1;
- }
- int countA = 0;
- printf("A={");
- input(&A, &countA, &capacityA);
- printf("}\n");
- // 初始化集合B
- int capacityB = 2;
- int* B = (int*)malloc(capacityB * sizeof(int));
- if (B == NULL) {
- printf("Memory allocation failed.\n");
- return 1;
- }
- int countB = 0;
- printf("B={");
- input(&B, &countB, &capacityB);
- printf("}\n");
- // 交集
- int inter[100], ci = 0;
- for (int i = 0; i < countA; ++i) {
- for (int j = 0; j < countB; ++j) {
- if (A[i] == B[j]) {
- inter[ci++] = A[i];
- break;
- }
- }
- }
- // 并集
- int uni[200], cu = 0;
- for (int i = 0; i < countA; ++i) uni[cu++] = A[i];
- for (int i = 0; i < countB; ++i) {
- int exists = 0;
- for (int j = 0; j < countA; ++j) {
- if (B[i] == A[j]) {
- exists = 1;
- break;
- }
- }
- if (!exists) uni[cu++] = B[i];
- }
- // 差集
- int diff[100], cd = 0;
- for (int i = 0; i < countA; ++i) {
- int inB = 0;
- for (int j = 0; j < countB; ++j) {
- if (A[i] == B[j]) {
- inB = 1;
- break;
- }
- }
- if (!inB) diff[cd++] = A[i];
- }
- printf("A交B={");
- for (int i = 0; i < ci; ++i) printf("%s%d", i ? ", " : "", inter[i]);
- printf("}\n");
- printf("A并B={");
- for (int i = 0; i < cu; ++i) printf("%s%d", i ? ", " : "", uni[i]);
- printf("}\n");
- printf("A-B={");
- for (int i = 0; i < cd; ++i) printf("%s%d", i ? ", " : "", diff[i]);
- printf("}\n");
- free(A);
- free(B);
- return 0;
- }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |