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>
// Define node structure
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to insert a node at the end of the list
void insertNode(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
// Function to print the list
void printList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
// Function to find the intersection of two lists
struct Node* intersection(struct Node* list1, struct Node* list2) {
struct Node* result = NULL;
struct Node* temp1 = list1;
while (temp1 != NULL) {
struct Node* temp2 = list2;
while (temp2 != NULL) {
if (temp1->data == temp2->data) {
insertNode(&result, temp1->data);
break;
}
temp2 = temp2->next;
}
temp1 = temp1->next;
}
return result;
}
// Function to find the union of two lists
struct Node* unionList(struct Node* list1, struct Node* list2) {
struct Node* result = NULL;
struct Node* temp1 = list1;
while (temp1 != NULL) {
insertNode(&result, temp1->data);
temp1 = temp1->next;
}
struct Node* temp2 = list2;
while (temp2 != NULL) {
int found = 0;
struct Node* temp3 = result;
while (temp3 != NULL) {
if (temp3->data == temp2->data) {
found = 1;
break;
}
temp3 = temp3->next;
}
if (!found) {
insertNode(&result, temp2->data);
}
temp2 = temp2->next;
}
return result;
}
int main() {
struct Node* list1 = NULL;
struct Node* list2 = NULL;
// Input for first list
printf("Enter elements for the first list (enter -1 to stop): ");
int data;
while (1) {
scanf("%d", &data);
if (data == -1) break;
insertNode(&list1, data);
}
// Input for second list
printf("Enter elements for the second list (enter -1 to stop): ");
while (1) {
scanf("%d", &data);
if (data == -1) break;
insertNode(&list2, data);
}
// Print the original lists
printf("\nFirst List: ");
printList(list1);
printf("Second List: ");
printList(list2);
// Find and print the intersection
struct Node* intersectionList = intersection(list1, list2);
printf("\nIntersection of the lists: ");
printList(intersectionList);
// Find and print the union
struct Node* unionListResult = unionList(list1, list2);
printf("\nUnion of the lists: ");
printList(unionListResult);
return 0;
}