Project 1 - Creation of user defined data type to implement the user interfaces for working with ‘Set’ (Mathematical Set theory)
#include <stdio.h>/* Header file */
#include <stdlib.h>/* Header file */
struct node /* A structure of linked list node */
{
int data;
struct node *next;
} *LLOne, *LLTwo, *unionLL, *intersection LL;
void initialize()
{
LLOne = LLTwo = NULL;
}
void insert(struct node **head, int num)/*Given a Inserts a node in front of a singly linked list. */
{
struct node* newNode = (struct node*) malloc(sizeof(struct node));/* Create a new Linked List node */
newNode->data = num;
newNode->next = *head;/* Next pointer of new node will point to head node of linked list */
*head = newNode;/* make new node as new head of linked list */
}
int search(struct node *head, int num) /* Searches an element in Linked List by linearly traversing from head to tail */
{
while (head != NULL)
{
if (head->data == num)
{
return 1;
}
head = head->next;
}
return 0;
}
struct node* findunion(struct node *LLOne, struct node *LLTwo) /*Returns the union of two given linked list */
{
unionLL = NULL;
struct node *temp = LLOne;/* Add all nodes of first Linked List to unionLL */
while(temp != NULL){
insert(&unionLL, temp->data);
temp = temp->next;
}
while(LLTwo != NULL)/* Insert those nodes of LLTwo which is not present in LLOne */
{
if(!search(LLOne, LLTwo->data))
{
insert(&unionLL, LLTwo->data);
}
LLTwo = LLTwo->next;
}
return unionLL;
}
struct node* intersection(struct node *LLOne, struct node *LLTwo)/* Returns the Linked List which contains common nodes of two given linked list */
{
intersectionLL = NULL;
while(LLOne != NULL) /* Search every element of LLOne in LLTwo,If found then add it to intersection List */
{
if(search(LLTwo, LLOne->data))
{
insert(&intersectionLL, LLOne->data);
}
LLOne = LLOne->next;
}
return intersectionLL;
}
void printLinkedList(struct node *nodePtr) /*Prints a linked list from head node till tail node*/
{
while (nodePtr != NULL) {
printf("%d", nodePtr->data);
nodePtr = nodePtr->next;
if(nodePtr != NULL)
printf(" ");
}
}
int main() {
int i, LLOneCount, LLTwoCount, temp;
initialize();
printf("Enter number of nodes in First Linked List\n");/* Creating First linked List*/
scanf("%d", &LLOneCount);
printf("Enter %d integers\n", LLOneCount);
for(i=0; i<LLOneCount; i++)
{
scanf("%d", &temp);
insert(&LLOne, temp);
}
printLinkedList(LLOne);
printf("\nEnter number of nodes in Second Linked List\n");
scanf("%d", &LLTwoCount);
printf("Enter %d integers\n", 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\nUnion Linked List\n");
printLinkedList(unionLL);
printf("\n\nIntersection Linked List\n");
printLinkedList(intersectionLL);
return 0;
}