Challenge

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

/*
* setheory.c
*
* Created on: 23-Mar-2023
* Author: Lalli
*/


#include
#include

// Define a linked list node for a set element

typedef struct Node {
int data;
struct Node* next;
} Node;

// Function to add an element to a set represented by a linked list
void addElement(Node** head, int data) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = data;
new_node->next = NULL;
if (*head == NULL) {
*head = new_node;
return;
}
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = new_node;
}

// Function to print the elements of a set represented by a linked list


void printSet(Node* head) {
printf("{ ");
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("}n");
}

// Function to compute the union of two sets represented by linked lists


Node* unionSet(Node* set1, Node* set2) {
Node* union_set = NULL;
while (set1 != NULL) {
addElement(&union_set, set1->data);
set1 = set1->next;
}
while (set2 != NULL) {
if (!isElement(set1, set2->data)) {
addElement(&union_set, set2->data);
}
set2 = set2->next;
}
return union_set;
}

// Function to compute the intersection of two sets represented by linked lists


Node* intersectSet(Node* set1, Node* set2) {
Node* intersect_set = NULL;
while (set1 != NULL) {
if (isElement(set2, set1->data)) {
addElement(&intersect_set, set1->data);
}
set1 = set1->next;
}
return intersect_set;
}

// Function to check if an element is present in a set represented by a linked list


int isElement(Node* head, int data) {
while (head != NULL) {
if (head->data == data) {
return 1;
}
head = head->next;
}
return 0;
}

int main() {
Node* set1 = NULL;
Node* set2 = NULL;

// add elements to set1
addElement(&set1, 1);
addElement(&set1, 2);
addElement(&set1, 3);
printf("Set 1: ");
printSet(set1);

// add elements to set2
addElement(&set2, 3);
addElement(&set2, 4);
addElement(&set2, 5);
printf("Set 2: ");
printSet(set2);

// compute the union of set1 and set2
Node* union_set = unionSet(set1, set2);
printf("Union of set1 and set2: ");
printSet(union_set);

// compute the intersection of set1 and set2
Node* intersect_set = intersectSet(set1, set2);
printf("Intersection of set1 and set2: ");
printSet(intersect_set);

return 0;
}

OUTPUT:

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.