Project 1 - Creation of user defined data type to implement the user interfaces for working with ‘Set’ (Mathematical Set theory) using Linked List
Program:
#include
#include
typedef enum {
FALSE,
TRUE
} boolean;
struct Node {
int value;
struct Node* next;
};
// function return the memory allocated to the new node
struct Node* createNode()
{
return (struct Node*) malloc(sizeof(struct Node));
}
// insert the node to end of list
void addValueToList(struct Node** p, int value)
{
struct Node *currentNode;
struct Node *newNode = createNode();
newNode->value = value;
newNode->next = NULL;
if (*p == NULL) {
*p = newNode;
return;
}
currentNode = *p;
while(currentNode->next != NULL) {
// do not add new node if value exist in the list
if (currentNode->value == value) {
free(newNode);
return;
}
currentNode = currentNode->next;
}
currentNode->next = newNode;
}
void printList(struct Node* currentNode)
{
while(currentNode != NULL) {
printf("%d\n", currentNode->value);
currentNode = currentNode->next;
}
}
boolean valueExistInList(struct Node *cNode, int value) {
while (cNode != NULL) {
if (cNode->value == value) {
return TRUE;
}
cNode = cNode->next;
}
return FALSE;
}
void printIntersections(struct Node *list1, struct Node *list2)
{
printf("printing intersection of data of two list\n");
while (list1 != NULL) {
if (valueExistInList(list2, list1->value) == TRUE) {
printf("%d\n", list1->value);
}
list1 = list1->next;
}
}
void printUnions(struct Node *list1, struct Node *list2)
{
struct Node *temp = list1;
printf("printing union of data of two list\n");
while (temp != NULL) {
printf("%d\n", temp->value);
temp = temp->next;
}
while (list2 != NULL) {
if (valueExistInList(list1, list2->value) == FALSE) {
printf("%d\n", list2->value);
}
list2 = list2->next;
}
}
int main()
{
unsigned short listSize1, listSize2;
int value;
struct Node *list1 = NULL, *list2 = NULL;
printf("Enter the size of list1:");
// read the size of list1
scanf("%hd", &listSize1);
while (listSize1--) {
// read values of list1
scanf("%d", &value);
addValueToList(&list1, value);
}
printf("Enter the size of list2:");
// read the size of list2
scanf("%hd", &listSize2);
while (listSize2--) {
// read values of list2
scanf("%d", &value);
addValueToList(&list2, value);
}
printf("Printing the list1:\n");
printList(list1);
printf("Printing the list2:\n");
printList(list2);
printIntersections(list1, list2);
printUnions(list1, list2);
return 0;
}
Response:
