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>

// Node structure for the linked list

struct Node {

int data;

struct Node* next;

};

// Function to create a new node

struct Node* createNode(int data) {

struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

newNode->data = data;

newNode->next = NULL;

return newNode;

}

// Insert a node at the end of the list

struct Node* insertAtEnd(struct Node* head, int data) {

struct Node* newNode = createNode(data);

if (head == NULL)

return newNode;

struct Node* temp = head;

while (temp->next != NULL)

temp = temp->next;

temp->next = newNode;

return head;

}

// Search if a value exists in the list

int search(struct Node* head, int key) {

while (head != NULL) {

if (head->data == key)

return 1;

head = head->next;

}

return 0;

}

// Build a linked list from an array

struct Node* buildListFromArray(int arr[], int size) {

struct Node* head = NULL;

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

if (!search(head, arr[i])) { // prevent duplicates

head = insertAtEnd(head, arr[i]);

}

}

return head;

}

// Print linked list

void printList(struct Node* head) {

while (head != NULL) {

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

head = head->next;

}

printf("NULL\n");

}

// Intersection of two sets

struct Node* intersection(struct Node* head1, struct Node* head2) {

struct Node* result = NULL;

while (head1 != NULL) {

if (search(head2, head1->data)) {

if (!search(result, head1->data)) {

result = insertAtEnd(result, head1->data);

}

}

head1 = head1->next;

}

return result;

}

// Union of two sets

struct Node* unionSet(struct Node* head1, struct Node* head2) {

struct Node* result = NULL;

while (head1 != NULL) {

if (!search(result, head1->data)) {

result = insertAtEnd(result, head1->data);

}

head1 = head1->next;

}

while (head2 != NULL) {

if (!search(result, head2->data)) {

result = insertAtEnd(result, head2->data);

}

head2 = head2->next;

}

return result;

}

// Main to test the project

int main() {

int arr1[] = {10, 20, 30, 40};

int arr2[] = {30, 40, 50, 60};

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

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

struct Node* set1 = buildListFromArray(arr1, size1);

struct Node* set2 = buildListFromArray(arr2, size2);

printf("Set 1: ");

printList(set1);

printf("Set 2: ");

printList(set2);

struct Node* union_result = unionSet(set1, set2);

struct Node* intersection_result = intersection(set1, set2);

printf("Union: ");

printList(union_result);

printf("Intersection: ");

printList(intersection_result);

return 0;

}

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.