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;
};

typedef struct Node Node;

// Function to create a new node
Node* createNode(int data)
{
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode != NULL) {
newNode->data = data;
newNode->next = NULL;
}
return newNode;
}

// Function to insert a node at the end of the linked list
void insertEnd(Node** head, int data)
{
Node* newNode = createNode(data);
if (newNode == NULL)
{
printf("Memory allocation failed!\n");
return;
}

if (*head == NULL)
{
*head = newNode;
} else {
Node* temp = *head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
}
}

// Function to print the linked list
void printList(Node* head)
{
Node* temp = head;
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

// Function to free the memory occupied by the linked list
void freeList(Node* head)
{
Node* temp;
while (head != NULL)
{
temp = head;
head = head->next;
free(temp);
}
}

// Function to find the union of two linked lists (sets)
Node* findUnion(Node* list1, Node* list2)
{
Node* result = NULL;
Node* temp1 = list1;
Node* temp2 = list2;

while (temp1 != NULL)
{
insertEnd(&result, temp1->data);
temp1 = temp1->next;
}

while (temp2 != NULL)
{
if (!contains(result, temp2->data))
{
insertEnd(&result, temp2->data);
}
temp2 = temp2->next;
}

return result;
}

// Function to check if the value exists in the linked list
int contains(Node* head, int value)
{
Node* temp = head;
while (temp != NULL)
{
if (temp->data == value)
{
return 1;
}
temp = temp->next;
}
return 0;
}

// Function to find the intersection of two linked lists (sets)
Node* findIntersection(Node* list1, Node* list2)
{
Node* result = NULL;
Node* temp1 = list1;

while (temp1 != NULL)
{
if (contains(list2, temp1->data))
{
insertEnd(&result, temp1->data);
}
temp1 = temp1->next;
}

return result;
}

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

// Insert elements into the first set (linked list)
insertEnd(&set1, 1);
insertEnd(&set1, 2);
insertEnd(&set1, 3);
insertEnd(&set1, 4);

// Insert elements into the second set (linked list)
insertEnd(&set2, 3);
insertEnd(&set2, 4);
insertEnd(&set2, 5);
insertEnd(&set2, 6);

printf("Set 1: ");
printList(set1);

printf("Set 2: ");
printList(set2);

Node* unionResult = findUnion(set1, set2);
printf("Union: ");
printList(unionResult);
freeList(unionResult);

Node* intersectionResult = findIntersection(set1, set2);
printf("Intersection: ");
printList(intersectionResult);
freeList(intersectionResult);

freeList(set1);
freeList(set2);

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.