Project 1 - Creation of user defined data type to implement the user interfaces for working with ‘Set’ (Mathematical Set theory) using Linked List
code:
#include <stdio.h>
#include <stdlib.h>
// Node structure for linked list
typedef struct Node {
int data;
struct Node* next;
} Node;
// Set structure
typedef struct Set {
Node* head;
} Set;
// Function to create an empty set
Set* createSet() {
Set* set = (Set*)malloc(sizeof(Set));
set->head = NULL;
return set;
}
// Function to check if a set is empty
int isEmpty(Set* set) {
return (set->head == NULL);
}
// Function to check if an element is present in the set
int isElementPresent(Set* set, int element) {
Node* current = set->head;
while (current != NULL) {
if (current->data == element) {
return 1; // Element found in the set
}
current = current->next;
}
return 0; // Element not found in the set
}
// Function to insert an element into the set
void insertElement(Set* set, int element) {
if (isElementPresent(set, element)) {
printf("Element already exists in the set.\n");
return;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = element;
newNode->next = set->head;
set->head = newNode;
printf("Element %d inserted into the set.\n", element);
}
// Function to delete an element from the set
void deleteElement(Set* set, int element) {
if (isEmpty(set)) {
printf("Set is empty. Cannot delete element.\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 deleted from the set.\n", element);
return;
}
prev = current;
current = current->next;
}
printf("Element not found in the set.\n");
}
// Function to display the elements of the set
void displaySet(Set* set) {
if (isEmpty(set)) {
printf("Set is empty.\n");
return;
}
Node* current = set->head;
printf("Set: ");
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
// Main function for testing the set operations
int main() {
Set* set = createSet();
insertElement(set, 5);
insertElement(set, 10);
insertElement(set, 15);
insertElement(set, 20);
displaySet(set);
deleteElement(set, 10);
deleteElement(set, 25);
displaySet(set);
return 0;
}
output screenshot:
