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>
// Structure for a node in the linked list
struct Node {
int data;
struct Node* next;
};
// Function to insert a new node at the end of the list
void insert(struct Node** head, int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if (*head == NULL) { // If list is empty, new node becomes the first node
*head = newNode;
return;
}
struct Node* temp = *head;
while (temp->next != NULL) { // Traverse to the last node
temp = temp->next;
}
temp->next = newNode;
}
// Function to print the linked list
void printList(struct Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
// Function to find the intersection of two lists
struct Node* findIntersection(struct Node* list1, struct Node* list2) {
struct Node* result = NULL;
struct Node* temp1 = list1;
while (temp1 != NULL) { // Traverse first list
struct Node* temp2 = list2;
while (temp2 != NULL) { // Compare with every element in second list
if (temp1->data == temp2->data) { // If elements match, add to result
insert(&result, temp1->data);
break;
}
temp2 = temp2->next;
}
temp1 = temp1->next;
}
return result;
}
// Function to find the union of two lists
struct Node* findUnion(struct Node* list1, struct Node* list2) {
struct Node* result = NULL;
struct Node* temp = list1;
while (temp != NULL) { // Copy all elements from list1
insert(&result, temp->data);
temp = temp->next;
}
temp = list2;
while (temp != NULL) { // Copy elements from list2 if not already present
struct Node* check = list1;
int exists = 0;
while (check != NULL) { // Check if the element already exists
if (check->data == temp->data) {
exists = 1;
break;
}
check = check->next;
}
if (!exists) {
insert(&result, temp->data);
}
temp = temp->next;
}
return result;
}
// Main function
int main() {
struct Node* list1 = NULL;
struct Node* list2 = NULL;
// Example data
insert(&list1, 1);
insert(&list1, 2);
insert(&list1, 3);
insert(&list1, 4);
insert(&list2, 3);
insert(&list2, 4);
insert(&list2, 5);
insert(&list2, 6);
printf("List 1: ");
printList(list1);
printf("List 2: ");
printList(list2);
struct Node* intersection = findIntersection(list1, list2);
printf("Intersection: ");
printList(intersection);
struct Node* unionList = findUnion(list1, list2);
printf("Union: ");
printList(unionList);
return 0;
}
