Project 1 - Creation of user defined data type to implement the user interfaces for working with ‘Set’ (Mathematical Set theory) using Linked List
#include
#include
struct Node { // Define a structure for a linked list node
int data;
struct Node* next;
};
struct Node* createNode(int data) { // Function to create a new node with the given data
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertNode(struct Node** head, int data) { // Function to insert a node at the end of a linked list
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
struct Node* findIntersection(struct Node* list1, struct Node* list2) {
struct Node* result = NULL;
while (list1 != NULL && list2 != NULL) {
if (list1->data == list2->data) {
insertNode(&result, list1->data);
list1 = list1->next;
list2 = list2->next;
} else if (list1->data < list2>data) {
list1 = list1->next;
} else {
list2 = list2->next;
}
}
return result;
}
struct Node* getUnion(struct Node* list1, struct Node* list2) {
struct Node* result = NULL;
while (list1 != NULL) {
insertNode(&result, list1->data);
list1 = list1->next;
}
while (list2 != NULL) {
if (!result || list2->data != result->data) {
insertNode(&result, list2->data);
}
list2 = list2->next;
}
return result;
}
void printList(struct Node* head) { // Function to print the elements of a linked list
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
int main() {
struct Node* list1 = NULL;
struct Node* list2 = NULL;
insertNode(&list1, 1);
insertNode(&list1, 2);
insertNode(&list1, 3);
insertNode(&list1, 4);
insertNode(&list2, 3);
insertNode(&list2, 4);
insertNode(&list2, 5);
insertNode(&list2, 6);
struct Node* intersection = findIntersection(list1, list2);
printf("Intersection: ");
printList(intersection);
struct Node* unionList = getUnion(list1, list2);
printf("Union: ");
printList(unionList);
return 0;
}
OUTPUT: