Project 1 - Creation of user defined data type to implement the user interfaces for working with ‘Set’ (Mathematical Set theory) using Linked List
OFFLINE BATCH
#include <stdio.h> //preprocessor function
#include<stdlib.h> //preprocessor function
#include<stdbool.h> //preprocessor function
struct Node
{
int data;//structure member
struct Node* nextptr;//structure member
};
void push(struct Node **ruso1, int new_data);//to insert node at beginning of linked list
bool isPresent(struct Node *head, int data);//to check if given data is present in list
struct Node *getUnion(struct Node *head1,struct Node *head2)//to get union of two list, head1,head2
{
struct Node *temp = NULL;
struct Node *t1 = head1, *t2 = head2;
// Insert all elements of list1 to the result list
while (t1 != NULL)
{
push(&temp,t1->data);
t1 = t1->nextptr;
}
// Insert those elements of list2 which are not
// present in result list
while (t2 != NULL)
{
if (!isPresent(temp,t2->data))
push(&temp,t2->data);
t2 = t2->nextptr;
}
return temp;
}
struct Node *getIntersection(struct Node* head1, struct Node* head2)//to get intersection of two list head1,head2
{
struct Node* temp = NULL;
struct Node* t1=head1;
//traverse list1.if the element is present in list2,then insert element to result
while(t1 != NULL)
{
if(isPresent(head2,t1->data))
push(&temp,t1->data);
t1=t1->nextptr;
}
return temp;
}
void push(struct Node **ruso1, int new_data)
{
//allocate node
struct Node* pree = (struct Node*)malloc(sizeof(struct Node));
pree->data = new_data;//link old list to new node
pree -> nextptr = *ruso1;
*ruso1=pree;
}
void printList(struct Node* ruso)//to print a linked list
{
while(ruso != NULL)
{
printf("%d ", ruso -> data);
ruso = ruso -> nextptr;
}
}
bool isPresent(struct Node* head, int data)
{
struct Node* t=head;
while(t !=NULL)
{
if(t->data == data)
return 1;
t=t->nextptr;
}
return 0;
}
int main()
{
//start with empty list
struct Node* head1=NULL;
struct Node* head2=NULL;
struct Node* Union=NULL;
struct Node* Intersection=NULL;
//creating list of head1
push(& head1 , 2);
push(& head1 , 7);
push(& head1 , 3);
push(& head1 , 5);
//creating list of head2
push(&head2 , 3);
push(&head2 , 6);
push(&head2 , 5);
push(&head2 , 1);
Union= getUnion(head1, head2);
Intersection = getIntersection(head1, head2);
printf("\n First List is : ");
printList(head1);
printf("\n Second List is : ");
printList(head2);
printf("\n Intersection is : ");
printList(Intersection);
printf("\n Union is : ");
printList(Union);
return 0;
}