C語言中可以使用數組、結構體、指針等數據結構來實現集合。
#define MAX_SIZE 100
int set[MAX_SIZE];
int size = 0;
void addElement(int element) {
set[size++] = element;
}
int contains(int element) {
for (int i = 0; i < size; i++) {
if (set[i] == element) {
return 1;
}
}
return 0;
}
void removeElement(int element) {
for (int i = 0; i < size; i++) {
if (set[i] == element) {
for (int j = i; j < size - 1; j++) {
set[j] = set[j + 1];
}
size--;
break;
}
}
}
#define MAX_SIZE 100
typedef struct {
int elements[MAX_SIZE];
int size;
} Set;
void addElement(Set *set, int element) {
set->elements[set->size++] = element;
}
int contains(Set *set, int element) {
for (int i = 0; i < set->size; i++) {
if (set->elements[i] == element) {
return 1;
}
}
return 0;
}
void removeElement(Set *set, int element) {
for (int i = 0; i < set->size; i++) {
if (set->elements[i] == element) {
for (int j = i; j < set->size - 1; j++) {
set->elements[j] = set->elements[j + 1];
}
set->size--;
break;
}
}
}
typedef struct {
int *elements;
int size;
} Set;
Set* createSet() {
Set *set = (Set*)malloc(sizeof(Set));
set->elements = (int*)malloc(sizeof(int) * MAX_SIZE);
set->size = 0;
return set;
}
void addElement(Set *set, int element) {
set->elements[set->size++] = element;
}
int contains(Set *set, int element) {
for (int i = 0; i < set->size; i++) {
if (set->elements[i] == element) {
return 1;
}
}
return 0;
}
void removeElement(Set *set, int element) {
for (int i = 0; i < set->size; i++) {
if (set->elements[i] == element) {
for (int j = i; j < set->size - 1; j++) {
set->elements[j] = set->elements[j + 1];
}
set->size--;
break;
}
}
}
void freeSet(Set *set) {
free(set->elements);
free(set);
}