Project 1 - Creation of user defined data type to implement the user interfaces for working with ‘Set’ (Mathematical Set theory) using Linked List
/*
* project1.c
*This C program defines a basic implementation of mathematical Set Theory operations for two linked lists, including union and intersection.
*
* Author: Nitish
*/
#include
#include
// Define a structure for a node in the linked list
struct Node {
int data;
struct Node* next;
};
// Function to insert a new element at the end of a linked list
void insertEnd(struct Node** head, int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// Function to perform the union of two linked lists
struct Node* unionLists(struct Node* list1, struct Node* list2) {
struct Node* result = NULL;
struct Node* temp1 = list1;
struct Node* temp2 = list2;
while (temp1 != NULL) {
insertEnd(&result, temp1->data);
temp1 = temp1->next;
}
while (temp2 != NULL) {
if (!search(result, temp2->data)) {
insertEnd(&result, temp2->data);
}
temp2 = temp2->next;
}
return result;
}
// Function to perform the intersection of two linked lists
struct Node* intersectionLists(struct Node* list1, struct Node* list2) {
struct Node* result = NULL;
struct Node* temp1 = list1;
while (temp1 != NULL) {
if (search(list2, temp1->data)) {
insertEnd(&result, temp1->data);
}
temp1 = temp1->next;
}
return result;
}
// Function to search for an element in a linked list
int search(struct Node* head, int value) {
struct Node* current = head;
while (current != NULL) {
if (current->data == value) {
return 1; // Element found
}
current = current->next;
}
return 0; // Element not found
}
// Function to print the elements of a linked list
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
struct Node* list1 = NULL;
struct Node* list2 = NULL;
struct Node* unionResult;
struct Node* intersectionResult;
// Insert elements into the first list
insertEnd(&list1, 1);
insertEnd(&list1, 2);
insertEnd(&list1, 3);
// Insert elements into the second list
insertEnd(&list2, 2);
insertEnd(&list2, 3);
insertEnd(&list2, 4);
printf("List 1: ");
printList(list1);
printf("List 2: ");
printList(list2);
unionResult = unionLists(list1, list2);
printf("Union: ");
printList(unionResult);
intersectionResult = intersectionLists(list1, list2);
printf("Intersection: ");
printList(intersectionResult);
return 0;
}