#include <stdio.h>
#include <stdlib.h>
/* Node structure for the linked list */
struct Node {
int data;
struct Node* next;
};
/* Function to add a node to the end of the linked list */
void addNode(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->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 perform the union of two sets */
struct Node* setUnion(struct Node* a, struct Node* b) {
struct Node* result = NULL;
/* Add all the elements of list a to the result */
while (a != NULL) {
addNode(&result, a->data);
a = a->next;
}
/* Add all the elements of list b to the result, skipping duplicates */
while (b != NULL) {
struct Node* current = result;
while (current != NULL) {
if (current->data == b->data) {
break;
}
current = current->next;
}
if (current == NULL) {
addNode(&result, b->data);
}
b = b->next;
}
return result;
}
/* Function to perform the intersection of two sets */
struct Node* setIntersection(struct Node* a, struct Node* b) {
struct Node* result = NULL;
/* Check each element of list a for membership in list b */
while (a != NULL) {
struct Node* current = b;
while (current != NULL) {
if (current->data == a->data) {
addNode(&result, a->data);
break;
}
current = current->next;
}
a = a->next;
}
return result;
}
/* Main function to test the implementation */
int main() {
/* Create the first set */
struct Node* setA = NULL;
addNode(&setA, 1);
addNode(&setA, 2);
addNode(&setA, 3);
addNode(&setA, 4);
printf("Set A: ");
printList(setA);
/* Create the second set */
struct Node* setB = NULL;
addNode(&setB, 3);
addNode(&setB, 4);
addNode(&setB, 5);
addNode(&setB, 6);
printf("Set B: ");
printList(setB);
/* Calculate and print the union of the two sets */
struct Node* unionSet = setUnion(setA, setB);
printf("Union: ");
printList(unionSet);
/* Calculate and print the intersection of the two sets */
struct Node* intersectionSet = setIntersection(setA, setB);
printf("Intersection: ");
printList(intersectionSet);
return 0;
}