Project 1 - Creation of user defined data type to implement the user interfaces for working with ‘Set’ (Mathematical Set theory) using Linked List
#include <stdio.h>
#include <stdlib.h>
// Structure for a set element
struct SetElement {
int value;
struct SetElement* next;
};
// Structure for the set
struct Set {
struct SetElement* head;
int size;
};
// Function to initialize a set
void initializeSet(struct Set* set) {
set->head = NULL;
set->size = 0;
}
// Function to check if an element is in the set
int isInSet(const struct Set* set, int value) {
struct SetElement* current = set->head;
while (current != NULL) {
if (current->value == value) {
return 1; // Element found in set
}
current = current->next;
}
return 0; // Element not found in set
}
// Function to add an element to the set
void addToSet(struct Set* set, int value) {
if (!isInSet(set, value)) {
struct SetElement* newElement = (struct SetElement*)malloc(sizeof(struct SetElement));
newElement->value = value;
newElement->next = set->head;
set->head = newElement;
set->size++;
}
}
// Function to remove an element from the set
void removeFromSet(struct Set* set, int value) {
if (set->head == NULL) {
return; // Set is empty
}
if (set->head->value == value) {
struct SetElement* temp = set->head;
set->head = set->head->next;
free(temp);
set->size--;
return;
}
struct SetElement* current = set->head;
while (current->next != NULL && current->next->value != value) {
current = current->next;
}
if (current->next != NULL) {
struct SetElement* temp = current->next;
current->next = current->next->next;
free(temp);
set->size--;
}
}
// Function to display the set
void displaySet(const struct Set* set) {
struct SetElement* current = set->head;
printf("{ ");
while (current != NULL) {
printf("%d ", current->value);
current = current->next;
}
printf("}\n");
}
int main() {
struct Set mySet;
initializeSet(&mySet);
// Add elements to the set
addToSet(&mySet, 10);
addToSet(&mySet, 20);
addToSet(&mySet, 30);
addToSet(&mySet, 20); // Should not add duplicate
// Display the set
printf("Set contents: ");
displaySet(&mySet);
// Remove an element
removeFromSet(&mySet, 20);
// Display the modified set
printf("Modified set contents: ");
displaySet(&mySet);
// Clean up memory (optional)
struct SetElement* current = mySet.head;
while (current != NULL) {
struct SetElement* temp = current;
current = current->next;
free(temp);
}
return 0;
}