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-1
1)
#include<stdio.h>
#include<stdlib.h>
// A structure of linked list node
struct node
{
int data;
struct node *next;
} *naA, *naB, *unionna, *intersectionna;
void initialize()
{
naA = naB = NULL;
}
//Given a Inserts a node in front of a singly linked list.
void insert(struct node **head, int num)
{
// Create a new Linked List 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 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 the union of two given linked list
struct node* findunion(struct node *naA, struct node *naB)
{
unionna = NULL;
// Add all nodes of first Linked List to unionna
struct node *temp = naA;
while(temp != NULL)
{
insert(&unionna, temp->data);
temp = temp->next;
}
// Insert those nodes of naB which is not present in LLOne
while(naB != NULL)
{
if(!search(naA, naB->data))
{
insert(&unionna, naB->data);
}
naB = naB->next;
}
return unionna;
}
//Returns the Linked List which contains common nodes of two given linked list
struct node* intersection(struct node *naA, struct node *naB)
{
intersectionna = NULL;
//Search every element of naA in naB, If found then add it to intersection List
while(naA != NULL)
{
if(search(naB, naA->data))
{
insert(&intersectionna, naA->data);
}
naA = naA->next;
}
return intersectionna;
}
//Prints a linked list from head node till 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, naACount, naBCount, temp;
initialize();
//Creating First linked List
printf("Enter number of nodes in first Linked List\n");
scanf("%d", &naACount);
printf("Enter %d integers\n", naACount);
for(i=0; i<naACount; i++)
{
scanf("%d", &temp);
insert(&naA, temp);
}
printLinkedList(naA);
printf("\nEnter number of nodes in second Linked List\n");
scanf("%d", &naBCount);
printf("Enter %d integers\n", naBCount);
for(i=0; i<naBCount; i++)
{
scanf("%d", &temp);
insert(&naB, temp);
}
printLinkedList(naB);
//printing Union of two given linked list
findunion(naA, naB);
intersection(naA, naB);
printf("\nUnion \n");
printLinkedList(unionna);
printf("\nIntersection\n");
printLinkedList(intersectionna);
return 0;
}
OUTPUT:
Enter number of nodes in first Linked List
2
Enter 2 integers
3 9
9-->3
Enter number of nodes in second Linked List
3
Enter 3 integers
895
6
9
9-->6-->895
Union
895-->6-->3-->9
Intersection
9