Project 1 - Creation of user defined data type to implement the user interfaces for working with ‘Set’ (Mathematical Set theory) using Linked List
Program
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* next;
};
typedef struct Node Node;
//creating Node function dynamically allocates memory for new node
Node* createNode(int data)
{
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL)
{
fprintf(stderr, "Memory allocation failed.\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
//insert function is responsible for adding a new node
void insert(Node** head, int data)
{
Node* newNode = createNode(data);
if (*head == NULL)
{
*head = newNode;
} else
{
Node* current = *head;
while (current->next != NULL)
{
current = current->next;
}
current->next = newNode;
}
}
//display function prints the elements of a linked list.
void display(Node* head)
{
Node* current = head;
while (current != NULL)
{
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
//setUnion function computes the union of two sets
Node* setUnion(Node* set1, Node* set2)
{
Node* result = NULL;
while (set1 != NULL)
{
insert(&result, set1->data);
set1 = set1->next;
}
while (set2 != NULL)
{
int data = set2->data;
Node* temp = result;
int found = 0;
while (temp != NULL)
{
if (temp->data == data)
{
found = 1;
break;
}
temp = temp->next;
}
if (!found)
{
insert(&result, data);
}
set2 = set2->next;
}
return result;
}
//setIntersection function computes the intersection of two sets
Node* setIntersection(Node* set1, Node* set2)
{
Node* result = NULL;
while (set1 != NULL)
{
int data = set1->data;
Node* temp = set2;
while (temp != NULL)
{
if (temp->data == data)
{
insert(&result, data);
break;
}
temp = temp->next;
}
set1 = set1->next;
}
return result;
}
int main()
{
Node* set1 = NULL;
Node* set2 = NULL;
int numElements;
printf("Enter the number of elements for Set 1:");
fflush(stdout);
scanf("%d", &numElements);
printf("Enter elements for Set 1:\n");
fflush(stdout);
for (int i=0; i<numElements; i++)
{
int data;
scanf("%d", &data);
insert(&set1, data);
}
printf("Enter the number of elements for Set 2:");
fflush(stdout);
scanf("%d", &numElements);
printf("Enter elements for Set 2:\n");
fflush(stdout);
for (int i=0;i<numElements; i++)
{
int data;
scanf("%d", &data);
insert(&set2, data);
}
printf("Set 1:");
fflush(stdout);
display(set1);
printf("Set 2:");
fflush(stdout);
display(set2);
Node* unionSet = setUnion(set1, set2);
Node* intersectionSet = setIntersection(set1, set2);
printf("Union:");
fflush(stdout);
display(unionSet);
printf("Intersection:");
fflush(stdout);
display(intersectionSet);
return 0;
}
OUTPUT
Enter the number of elements for Set 1:3
Enter elements for Set 1:
1
2
3
Enter the number of elements for Set 2:4
Enter elements for Set 2:
2
3
1
5
Set 1:1 2 3
Set 2:2 3 1 5
Union:1 2 3 5
Intersection:1 2 3