Project 1 - Creation of user defined data type to implement the user interfaces for working with ‘Set’ (Mathematical Set theory) using Linked List
1)
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
// linked list node
struct node{
int data;
struct node* next;
};
//fun declaration
void push(struct node** head_ref, int new_data);
int present (struct node* head,int data);
//fun to get union of two linked list head1 and head2
struct node* getunion(struct node* head1,struct node* head2)
{
struct node* result= NULL;
struct node* t1=head1,*t2=head2;
//insert all elementof list 1
while(t1 != NULL)
{
push(&result,t1->data);
t1=t1->next;
}
// insert all element list2
while(t2 != NULL)
{
if( !present(result,t2->data))
{
push(&result,t2->data);
}
t2=t2->next;
}
return result;
}
//fun to get intersection of two linked list
struct node* getintersection(struct node*head1,struct node* head2)
{
struct node* result=NULL;
struct node*t1=head1;
//traverse list1
while(t1 != NULL)
{
if(present(head2,t1->data))
{
push(&result,t1->data);
}
t1=t1->next;
}
return result;
}
//a utility fun to insert a node of linked list
void push(struct node**head_ref,int new_data)
{
//allocate node
struct node* new_node =(struct node*)malloc(sizeof(struct node));
//put in the data
new_node->data=new_data;
new_node->next=(*head_ref);
//move the head to point to new node
(*head_ref)=new_node;
}
//fun to print alinked listr
void printlist(struct node* node)
{
while(node != NULL)
{
printf("%d",node->data);
node=node->next;
}
}
//fun that reutrn true if data is present in linked list
int present(struct node* head,int data)
{
struct node*t= head;
while(t != NULL)
{
if(t->data==data)
{
return 1;
}
t=t->next;
}
return 0;
}
//drive the proogram to test the fun
int main()
{
int n ,m ,temp;
printf("enter the value of number in linked list: ");
fflush(stdout);
scanf("%d%d",&n,&m);
struct node* head1=NULL;
struct node* head2=NULL;
struct node* intersecn=NULL;
struct node* unin= NULL;
//for loopfor linked list 1
for (int i=0;i<n;i++)
{
printf("enter the value in linked list1 %d:",i);
fflush(stdout);
scanf("%d",&temp);
push(&head1,temp);
}
//for loopfor linked list 2
for (int i=0;i<m;i++)
{
printf("enter the value in linked list2 %d:",i);
fflush(stdout);
scanf("%d",&temp);
push(&head2,temp);
}
//call the function of intersection
intersecn= getintersection(head1,head2);
//call the fun of union
unin= getunion(head1,head2);
printf("\n first list is:");
// call the function pointer arugment
printlist(head1);
printf("\n second list is:");
printlist(head2);
printf("\n intersection list is:");
printlist(intersecn);
printf("\n union list is:");
printlist(unin);
return 0;
}
output;
