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>
#include <string.h>
// Node structure for linked list
struct Node {
int data;
struct Node* next;
};
// Function to insert a node at the end of a linked list
void insertEnd(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* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// Function to check if a value is already present in the linked list
int contains(struct Node* head, int value) {
while (head != NULL) {
if (head->data == value) {
return 1; // Value is already present
}
head = head->next;
}
return 0; // Value is not present
}
// Function to print the elements of a linked list
void printList(struct Node* head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
// Function to find the intersection of two linked lists
void findIntersection(struct Node* list1, struct Node* list2) {
while (list1 != NULL) {
struct Node* temp = list2;
while (temp != NULL) {
if (list1->data == temp->data) {
printf("Intersection found at data: %d\n", list1->data);
break;
}
temp = temp->next;
}
list1 = list1->next;
}
}
// Function to find and print the union of two linked lists
void findunion(struct Node* list1, struct Node* list2) {
struct Node* unionList = NULL;
// Traverse the first list and add elements to the union list
while (list1 != NULL) {
insertEnd(&unionList, list1->data);
list1 = list1->next;
}
// Traverse the second list and add non-duplicate elements to the union list
while (list2 != NULL) {
if (!contains(unionList, list2->data)) {
insertEnd(&unionList, list2->data);
}
list2 = list2->next;
}
// Print the union list
printList(unionList);
}
int main() {
// Initialize two linked lists
struct Node* list1 = NULL;
struct Node* list2 = NULL;
// Insert nodes into the first list
insertEnd(&list1, 1);
insertEnd(&list1, 2);
insertEnd(&list1, 3);
// Insert nodes into the second list
insertEnd(&list2, 2);
insertEnd(&list2, 3);
insertEnd(&list2, 4);
// Find intersection of two lists
printf("Intersection of lists:\n");
findIntersection(list1, list2);
// Find union of two lists
printf("Union of lists:\n");
findunion(list1, list2);
return 0;
}