Challenge

Project 1 - Creation of user defined data type to implement the user interfaces for working with ‘Set’ (Mathematical Set theory) using Linked List

1.

#include <stdio.h>

#include <stdlib.h>

// Define structure for a linked list node

struct Node {

int data;

struct Node* next;

};

// Function to create a new node

struct Node* createNode(int value) {

struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

newNode->data = value;

newNode->next = NULL;

return newNode;

}

// Function to insert a node into a linked list

void insertNode(struct Node** head, int value) {

struct Node* newNode = createNode(value);

newNode->next = *head;

*head = newNode;

}

// Function to check if a value exists in a linked list

int exists(struct Node* head, int value) {

while (head != NULL) {

if (head->data == value) return 1;

head = head->next;

}

return 0;

}

// Function to compute union of two lists

struct Node* getUnion(struct Node* list1, struct Node* list2) {

struct Node* unionList = NULL;

// Insert elements of list1

while (list1 != NULL) {

insertNode(&unionList, list1->data);

list1 = list1->next;

}

// Insert elements of list2 (if not already in unionList)

while (list2 != NULL) {

if (!exists(unionList, list2->data)) {

insertNode(&unionList, list2->data);

}

list2 = list2->next;

}

return unionList;

}

// Function to compute intersection of two lists

struct Node* getIntersection(struct Node* list1, struct Node* list2) {

struct Node* intersectionList = NULL;

while (list1 != NULL) {

if (exists(list2, list1->data)) {

insertNode(&intersectionList, list1->data);

}

list1 = list1->next;

}

return intersectionList;

}

// Function to print the linked list

void printList(struct Node* head) {

while (head != NULL) {

printf("%d -> ", head->data);

head = head->next;

}

printf("NULL\n");

}

// Main function

int main() {

struct Node* list1 = NULL;

struct Node* list2 = NULL;

int n1, n2, value;

// Input for first list

printf("Enter number of elements in first list: ");

scanf("%d", &n1);

printf("Enter elements:\n");

for (int i = 0; i < n1; i++) {

scanf("%d", &value);

insertNode(&list1, value);

}

// Input for second list

printf("Enter number of elements in second list: ");

scanf("%d", &n2);

printf("Enter elements:\n");

for (int i = 0; i < n2; i++) {

scanf("%d", &value);

insertNode(&list2, value);

}

// Compute union and intersection

struct Node* unionList = getUnion(list1, list2);

struct Node* intersectionList = getIntersection(list1, list2);

// Print results

printf("\nUnion of lists:\n");

printList(unionList);

printf("\nIntersection of lists:\n");

printList(intersectionList);

return 0;

}

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.