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>

// Function prototypes

int* unionOfLists(int list1[], int size1, int list2[], int size2, int* resultSize);

int* intersectionOfLists(int list1[], int size1, int list2[], int size2, int* resultSize);

void printList(int list[], int size);

int main() {

int list1[] = {1, 2, 3, 4, 5};

int list2[] = {3, 4, 5, 6, 7};

int size1 = sizeof(list1) / sizeof(list1[0]);

int size2 = sizeof(list2) / sizeof(list2[0]);

int unionSize, intersectionSize;

int *unionResult = unionOfLists(list1, size1, list2, size2, &unionSize);

int *intersectionResult = intersectionOfLists(list1, size1, list2, size2, &intersectionSize);

printf("Union: ");

printList(unionResult, unionSize);

printf("Intersection: ");

printList(intersectionResult, intersectionSize);

// Free dynamically allocated memory

free(unionResult);

free(intersectionResult);

return 0;

}

// Function to calculate the union of two lists

int* unionOfLists(int list1[], int size1, int list2[], int size2, int* resultSize) {

int maxSize = size1 + size2;

int *result = (int*)malloc(maxSize * sizeof(int));

int i, j, k = 0;

for (i = 0; i < size1; i++) {

result[k++] = list1[i];

}

for (i = 0; i < size2; i++) {

int found = 0;

for (j = 0; j < size1; j++) {

if (list2[i] == list1[j]) {

found = 1;

break;

}

}

if (!found) {

result[k++] = list2[i];

}

}

*resultSize = k;

return result;

}

// Function to calculate the intersection of two lists

int* intersectionOfLists(int list1[], int size1, int list2[], int size2, int* resultSize) {

int *result = (int*)malloc(size1 * sizeof(int));

int i, j, k = 0;

for (i = 0; i < size1; i++) {

for (j = 0; j < size2; j++) {

if (list1[i] == list2[j]) {

result[k++] = list1[i];

break;

}

}

}

*resultSize = k;

return result;

}

// Function to print a list

void printList(int list[], int size) {

for (int i = 0; i < size; i++) {

printf("%d ", list[i]);

}

printf("\n");

}

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.