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>
// A structure of linked list node
struct node
{
int data;
struct node* next;
} *LLOne, *LLTwo, *unionLL, *intersectionLL;
void initialize()
{
LLOne = LLTwo = NULL;
}
// insert a node in a singly linked list
void insert(struct node** head, int num)
{
// create a new linked list
struct node*newNode = (struct node*)malloc(sizeof( struct node));
newNode-> data = num;
// next pointer of new node will point to head node of linked list
newNode->next = *head;
// make new node as new head of linked list
*head = newNode;
}
// search an element in linked list by linearly traversing from head to tail
int search(struct node* head, int num)
{
while(head!= NULL)
{
if(head->data == num)
{
return 1;
}
head = head-> next;
}
return 0;
}
//returns union of two linked list
struct node* findunion(struct node *LLOne, struct node *LLTwo)
{
unionLL= NULL;
// add all nodes of first linked list to unionLL
struct node* temp = LLOne;
while(temp!=NULL)
{
insert(&unionLL, temp-> data);
temp = temp-> next;
}
// insert those nodes of LLTwo
while(LLTwo!= NULL)
{
if(!search(LLOne, LLTwo-> data))
{
insert(&union, LLTwo-> data);
}
LLTwo = LLTwo-> next;
}
return unionLL;
}
// returns the linked list which contains common nodes of two given linked list
struct node* intersection(struct node *LLOne, struct node *LLTwo)
{
intersectionLL = NULL;
// search every element of LLone in LLTwo, if found then ADD in intersection list
while(LLOne != NULL)
{
if(search(LLTwo, LLOne-> data))
{
insert(&intersectionLL, LLOne->data);
}
LLOne = LLOne->next;
}
return intersectionLL;
}
// print a linked list from head node to tail node
void printLinkedList(struct node *nodePtr)
{
while (nodePtr != NULL)
{
printf("%d", nodePtr->data);
nodePtr = nodePtr-> next;
if(nodePtr != NULL)
printf("--->");
}
}
int main()
{
int i, LLOneCount, LLTwoCount, temp;
initialize();
// creating first linked list
printf("Enter number of nodes in first linked listn");
scanf("%d", &LLOneCount);
printf("Enter %d integersn", LLOneCount);
for(i=0; i<LLOneCount; i++)
{
scanf("%d", &temp);
insert(&LLOne , temp);
}
printLinkedList(LLOne);
printf("n Enter number of nodes in second linked listn");
scanf("%d", &LLTwoCount);
printf("Enter %d integersn", LLTwoCount);
for(i=0; i<LLTwoCount; i++)
{
scanf("%d", &temp);
insert(&LLTwo , temp);
}
printLinkedList(LLTwo);
// printing union of two given linked list
findunion(LLOne, LLTwo);
intersection(LLOne, LLTwo);
printf("n Union Linked Listn");
printLinkedList(unionLL);
printf("n Intersection Linked Listn");
printfLinkedList(intersectionLL);
return 0;
}
