Challenge

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>


struct node {
int data;
struct node *next;
};


struct set {
struct node *head;
};


struct node *create_node(int data) {
struct node *new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = data;
new_node->next = NULL;
return new_node;
}


void insert_node(struct set *set_ptr, int data) {
struct node *new_node = create_node(data);
if (set_ptr->head == NULL) {
set_ptr->head = new_node;
} else {
struct node *curr_node = set_ptr->head;
while (curr_node->next != NULL) {
curr_node = curr_node->next;
}
curr_node->next = new_node;
}
}


struct set intersection(struct set set1, struct set set2) {
struct set result_set;
result_set.head = NULL;
struct node *curr_node = set1.head;
while (curr_node != NULL) {
if (contains(set2, curr_node->data)) {
insert_node(&result_set, curr_node->data);
}
curr_node = curr_node->next;
}
return result_set;
}


struct set union_set(struct set set1, struct set set2) {
struct set result_set;
result_set.head = NULL;
struct node *curr_node = set1.head;
while (curr_node != NULL) {
insert_node(&result_set, curr_node->data);
curr_node = curr_node->next;
}
curr_node = set2.head;
while (curr_node != NULL) {
if (!contains(result_set, curr_node->data)) {
insert_node(&result_set, curr_node->data);
}
curr_node = curr_node->next;
}
return result_set;
}

// Method to check if a value is present in the set
int contains(struct set set_ptr, int value) {
struct node *curr_node = set_ptr.head;
while (curr_node != NULL) {
if (curr_node->data == value) {
return 1;
}
curr_node = curr_node->next;
}
return 0;
}


void print_list(struct node *node_ptr) {
while (node_ptr != NULL) {
printf("%d ", node_ptr->data);
node_ptr = node_ptr->next;
}
printf("\n");
}

int main() {
// Create two sets
struct set set1 = { NULL };
struct set set2 = { NULL };


insert_node(&set1, 1);
insert_node(&set1, 2);
insert_node(&set1, 3);


insert_node(&set2, 2);
insert_node(&set2, 3);
insert_node(&set2, 4);


struct set intersection_set = intersection(set1, set2);
printf("Intersection of the two sets: ");
print_list(intersection_set.head);

}

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.