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;
} *LL1, *LL2, *unionLL, *intersectionLL;
void initialize()
{
LL1 = LL2 = NULL;
}
/* Inserting new node at the beginning*/
void insert(struct node **head, int num)
{
/* Create a new node */
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;
}
/* Searches an element in Linked List by linear traversing*/
int search(struct node *head, int num)
{
while (head != NULL)
{
if (head->data == num)
{
return 1;
}
head = head->next;
}
return 0;
}
/Returns the union of two given linked list/
struct node* findunion(struct node *LL1, struct node *LL2)
{
unionLL = NULL;
/* Add all nodes of first Linked List to unionLL */
struct node *temp = LL1;
while(temp != NULL)
{
insert(&unionLL, temp->data);
temp = temp->next;
}
/* Insert those nodes of LL2 which are not present in LL1 */
while(LL2 != NULL)
{
if(!search(LL1, LL2->data))
{
insert(&unionLL, LL2->data);
}
LL2 = LL2->next;
}
return unionLL;
}
/Returns the Linked List which contains common nodes of two given linked list/
struct node* intersection(struct node *LL1, struct node *LL2)
{
intersectionLL = NULL;
/* Search every element of LL1 in LL2,
If found then add it to intersection List */
while(LL1 != NULL)
{
if(search(LL2, LL1->data))
{
insert(&intersectionLL, LL1->data);
}
LL1 = LL1->next;
}
return intersectionLL;
}
void printLinkedList(struct node *nodePtr)
{
while (nodePtr != NULL)
{
printf("%d ", nodePtr->data);
nodePtr = nodePtr->next;
}
}
int main()
{
int i, LL1Count, LL2Count, temp;
initialize();
/* Creating First linked List*/
printf("Enter number of nodes in first Linked List\n");
fflush(stdout);
scanf("%d", &LL1Count);
printf("Enter %d integers\n", LL1Count);
fflush(stdout);
for(i=0; i<LL1Count; i++)
{
scanf("%d", &temp);
insert(&LL1, temp);
}
printLinkedList(LL1);
/* Creating Second linked list */
printf("\nEnter number of nodes in second Linked List\n");
fflush(stdout);
scanf("%d", &LL2Count);
printf("Enter %d integers\n", LL2Count);
fflush(stdout);
for(i=0; i<LL2Count; i++)
{
scanf("%d", &temp);
insert(&LL2, temp);
}
printLinkedList(LL2);
/* printing Union and Intersection of two given linked list */
findunion(LL1, LL2);
intersection(LL1, LL2);
printf("\nUnion Linked List\n");
printLinkedList(unionLL);
printf("\nIntersection Linked List\n");
printLinkedList(intersectionLL);
return 0;
}