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>
//Define the nodes
typedef struct node
{
intdata;
structnode *next;//self referential node
}Node;
//Define the function
Node *insert_node(Node *head_ref, int n);
void display_list(Node *head_ref);
Node *getunion(Node *head_ptr1, Node *head_ptr2);
Node *getintersec(Node *head_ptr1, Node *head_ptr2);
int compare(Node *head, int data);
//Declaring the variables in structure
static Node *head, *head1, *head2, *head_union, *head_intersection, *tail, *newnode, *res_union, *res_intersection;
int main()
{
intfirst_set_nodes = 0, first_set_items = 0;
intsecond_set_nodes = 0, second_set_items = 0;
printf("Enter the number of Elements in the first Set: ");
fflush(stdout);
scanf("%d", &first_set_nodes);
printf("Enter All %d elements: ", first_set_nodes);
for(inti = 0; i < first_set_nodes; i++ )
{
fflush(stdout);
scanf("%d",&first_set_items);
head1 = insert_node(head1,first_set_items);
}
display_list(head1);
printf("\n");
printf("Enter the number of Elements in the second Set: ");
fflush(stdout);
scanf("%d", &second_set_nodes);
printf("Enter All %d elements: ", second_set_nodes);
for(inti = 0; i < second_set_nodes; i++ )
{
fflush(stdout);
scanf("%d",&second_set_items);
head2 = insert_node(head2,second_set_items);
}
display_list(head2);
printf("\n");
res_union = getunion(head1, head2);
printf("The union of sets : ");
display_list(res_union);
printf("\n");
res_intersection = getintersec(head1, head2);
printf("The intersection of sets : ");
display_list(res_intersection);
}
Node *insert_node(Node *head_ref, int n)
{
newnode = (Node*)malloc(sizeof(Node));
newnode->data = n;
newnode->next = head_ref;
head_ref = newnode;
returnhead_ref;
}
void display_list(Node *head_ref)
{
if(head_ref == 0)
{
printf("List is empty!");
}
else
{
tail = head_ref;
while(tail != 0)
{
printf("%d ",tail-> data);//prints the data of current node
tail = tail->next;
}
}
}
Node *getunion(Node *head_ptr1, Node *head_ptr2)
{
while(head_ptr1 != 0)
{
head_union = insert_node(head_union,head_ptr1->data);
head_ptr1 = head_ptr1->next;
}
while(head_ptr2 != 0)
{
if(!compare(head_union, head_ptr2->data))
head_union = insert_node(head_union,head_ptr2->data);
head_ptr2 = head_ptr2->next;
}
returnhead_union;
}
int compare(Node *head, int data)
{
while(head != NULL)
{
if(head->data == data)
return1;
head = head->next;
}
return0;
}
Node *getintersec(Node *head_ptr1, Node *head_ptr2)
{
while(head_ptr1 != 0)
{
if(compare(head_ptr2, head_ptr1->data))
head_intersection = insert_node(head_intersection, head_ptr1->data);
head_ptr1 = head_ptr1->next;
}
returnhead_intersection;
}