Challenge

Project 1 - Creation of user defined data type to implement the user interfaces for working with ‘Set’ (Mathematical Set theory) using Linked List

// Define the structure for a set

struct set {

int data;

struct set *next;

};

// Create a new set

struct set *new_set(int data) {

struct set *set = malloc(sizeof(struct set));

set->data = data;

set->next = NULL;

return set;

}

// Add an element to a set

void add_element(struct set *set, int data) {

while (set->next != NULL && set->next->data < data) {

set = set->next;

}

struct set *new_element = new_set(data);

new_element->next = set->next;

set->next = new_element;

}

// Remove an element from a set

void remove_element(struct set *set, int data) {

while (set->next != NULL && set->next->data != data) {

set = set->next;

}

if (set->next != NULL) {

struct set *next_element = set->next->next;

free(set->next);

set->next = next_element;

}

}

// Check if an element is in a set

bool is_element_in_set(struct set *set, int data) {

while (set != NULL && set->data != data) {

set = set->next;

}

return set != NULL;

}

// Get the size of a set

int size_of_set(struct set *set) {

int size = 0;

while (set != NULL) {

size++;

set = set->next;

}

return size;

}

// Print a set

void print_set(struct set *set) {

while (set != NULL) {

printf("%d ", set->data);

set = set->next;

}

printf("\n");

}

// Create a union of two sets

struct set *union_of_sets(struct set *set1, struct set *set2) {

struct set *union_set = new_set(0);

while (set1 != NULL) {

add_element(union_set, set1->data);

set1 = set1->next;

}

while (set2 != NULL) {

add_element(union_set, set2->data);

set2 = set2->next;

}

return union_set;

}

// Create an intersection of two sets

struct set *intersection_of_sets(struct set *set1, struct set *set2) {

struct set *intersection_set = new_set(0);

while (set1 != NULL) {

if (is_element_in_set(set2, set1->data)) {

add_element(intersecti

on_set, set1->data);

}

set1 = set1->next;

}

return intersection_set;

}

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.