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>
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct Set {
Node* head;
} Set;
Set* createSet() {
Set* set = (Set*)malloc(sizeof(Set));
set->head = NULL;
return set;
}
int isEmpty(Set* set) {
return (set->head == NULL);
}
int contains(Set* set, int element) {
Node* current = set->head;
while (current != NULL) {
if (current->data == element) {
return 1;
}
current = current->next;
}
return 0;
}
void addElement(Set* set, int element) {
if (contains(set, element)) {
printf("Element already exists in the set.\n");
return;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = element;
newNode->next = NULL;
if (set->head == NULL) {
set->head = newNode;
} else {
Node* current = set->head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
printf("Element %d added to the set.\n", element);
}
void removeElement(Set* set, int element) {
if (!contains(set, element)) {
printf("Element does not exist in the set.\n");
return;
}
Node* current = set->head;
Node* prev = NULL;
while (current != NULL) {
if (current->data == element) {
if (prev == NULL) {
set->head = current->next;
} else {
prev->next = current->next;
}
free(current);
printf("Element %d removed from the set.\n", element);
return;
}
prev = current;
current = current->next;
}
}
void displaySet(Set* set) {
Node* current = set->head;
if (isEmpty(set)) {
printf("Set is empty.\n");
return;
}
printf("Set elements: ");
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
void clearSet(Set* set) {
Node* current = set->head;
while (current != NULL) {
Node* temp = current;
current = current->next;
free(temp);
}
set->head = NULL;
printf("Set cleared.\n");
}
int main() {
Set* set = createSet();
addElement(set, 5);
addElement(set, 10);
addElement(set, 5);
displaySet(set);
removeElement(set, 10);
removeElement(set, 20);
displaySet(set);
clearSet(set);
displaySet(set);
return 0;
}
