Project 1 - Creation of user defined data type to implement the user interfaces for working with ‘Set’ (Mathematical Set theory) using Linked List
offine batch-2
#include <stdbool.h>
#include <stdio.h> // preprocessor
#include <stdlib.h>
struct node //structure declaration
{
int data;
struct node *next; //self referential structure declaration
};
//function declaration
void push(struct node**head_ref,int key);
int isPresent(struct node *head,int data);
// Function to get union of two linked lists head1 and head2
struct node *getUnion(struct node *head1,struct node *head2)
{
struct node *result=NULL;
struct node *r1=head1,*r2=head2;
// Insert all elements of list1 to the result list
while (r1!=NULL)
{
push(&result,r1->data);
r1=r1->next;
}
// Insert those elements of list2 which are not present in result list
while (r2!=NULL)
{
if(!isPresent(result,r2->data))
{
push(&result,r2->data);
}
r2=r2->next;
}
return result;
}
// Function to get intersection of two linked lists head1 and head2
struct node* getIntersection(struct node* head1,struct node* head2)
{
struct node* result = NULL;
struct node* t1 = head1;
// Traverse list1 and search each element of it in list2.
// If the element is present in list 2, then
// insert the element to result
while (t1 != NULL) {
if (isPresent(head2, t1->data))
push(&result, t1->data);
t1 = t1->next;
}
return result;
}
// A function to insert a node at the beginning of a linked list
void push(struct node**head_ref,int data)
{
struct node *newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=data;
newnode->next=(*head_ref);
(*head_ref)=newnode;
}
// A function to print a linked list
void display(struct node*head)
{
struct node *t;
t=head;
while(t!=NULL)
{
printf("%d\t",t->data);
t=t->next;
}
}
// A function that returns true if data is present in linked list else return false
int isPresent(struct node* head, int data)
{
struct node* t = head;
while (t != NULL) {
if (t->data == data)
return 1;
t = t->next;
}
return 0;
}
//Driver program to test above function
int main() // main function
{
int a,n,c; // declaration datatype and variable
printf("Enter the num of node for both linked list:"); // input from user
scanf("%d%d",&a,&c);
/* Start with the empty list */
struct node *head1=NULL;
struct node *head2=NULL;
struct node *unin=NULL;
struct node *intersc=NULL;
//for loop for link list1
for (int i=0;i<a;i++)
{
printf("Enter a list1-%d:",i);
scanf("%d",&n);
push(&head1,n);
}
//for loop for link list2
for (int i=0;i<c;i++)
{
printf("Enter a list2-%d:",i);
scanf("%d",&n);
push(&head2,n);
}
printf("\nlist1 :");
display(head1);
printf("\nlist2 :");
display(head2);
//call the function of union
unin=getUnion(head1,head2);
//call the function of intersection
intersc=getIntersection(head1,head2);
printf("\nunion :");
display(unin);
printf("\nintersection :");
display(intersc);
return 0;
}

