Project 1 - Creation of user defined data type to implement the user interfaces for working with ‘Set’ (Mathematical Set theory) using Linked List
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 for linked list
struct node {
int data;
struct node *next;
} *One, *Two, *Union, *intersection;
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;
newNode->next = *head;
*head = newNode;//make new node as new head of linked list
}
// Searches an element in Linked List by linearly 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 *One, struct node *Two) {
Union = NULL;
// Add all nodes of first Linked List to union
struct node *temp = One;
while(temp != NULL){
insert(&Union, temp->data);
temp = temp->next;
}
while(Two != NULL){
if(!search(One, Two->data)){
insert(&Union, Two->data);
}
Two = Two->next;
}
return Union;
}
//Returns the Linked List which contains common nodes of two given linked list
struct node* intersect(struct node *One, struct node *Two) {
intersection= 0;
while(One != NULL){
if(search(Two, One->data)){
insert(&intersection, One->data);
}
One = One->next;
}
return intersection;
}
//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;
}
}
int main() {
int i, OneCount, TwoCount, temp;
One=Two=NULL;
// Creating First linked List
printf("Enter number of nodes in first Linked List\n");
scanf("%d", &OneCount);
printf("Enter %d integers\n", OneCount);
for(i=0; i<OneCount; i++){
scanf("%d", &temp);
insert(&One, temp);
}
printLinkedList(One);
printf("\nEnter number of nodes in second Linked List\n");
scanf("%d", &TwoCount);
printf("Enter %d integers\n", TwoCount);
for(i=0; i<TwoCount; i++){
scanf("%d", &temp);
insert(&Two, temp);
}
printLinkedList(Two);
// printing Union of two given linked list
findunion(One, Two);
intersect(One, Two);
printf("\nUnion Linked List\n");
printLinkedList(Union);
printf("\nIntersection Linked List\n");
printLinkedList(intersection);
return 0;
}