Challenge

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 a node structure for the linked list

typedef struct Node {

int data;

struct Node* next;

} Node;

// Function to create a new node

Node* createNode(int data) {

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

newNode->data = data;

newNode->next = NULL;

return newNode;

}

// Function to insert a node at the end of the list

void insertNode(Node** head, int data) {

Node* newNode = createNode(data);

if (*head == NULL) {

*head = newNode;

return;

}

Node* temp = *head;

while (temp->next != NULL) {

temp = temp->next;

}

temp->next = newNode;

}

// Function to print the list

void printList(Node* head) {

Node* temp = head;

while (temp != NULL) {

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

temp = temp->next;

}

printf("NULL\n");

}

// Function to find the intersection of two lists

Node* intersection(Node* head1, Node* head2) {

Node* result = NULL;

Node* temp1 = head1;

while (temp1 != NULL) {

Node* temp2 = head2;

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

Node* unionOfLists(Node* head1, Node* head2) {

Node* result = NULL;

Node* temp = head1;

while (temp != NULL) {

insertNode(&result, temp->data);

temp = temp->next;

}

temp = head2;

while (temp != NULL) {

Node* temp2 = result;

int found = 0;

while (temp2 != NULL) {

if (temp2->data == temp->data) {

found = 1;

break;

}

temp2 = temp2->next;

}

if (!found) {

insertNode(&result, temp->data);

}

temp = temp->next;

}

return result;

}

int main() {

Node* list1 = NULL;

Node* list2 = NULL;

// Insert data into the first list

insertNode(&list1, 1);

insertNode(&list1, 2);

insertNode(&list1, 3);

insertNode(&list1, 4);

insertNode(&list1, 5);

// Insert data into the second list

insertNode(&list2, 4);

insertNode(&list2, 5);

insertNode(&list2, 6);

insertNode(&list2, 7);

insertNode(&list2, 8);

// Print the original lists

printf("List 1: ");

printList(list1);

printf("List 2: ");

printList(list2);

// Find and print the intersection of the lists

Node* intersect = intersection(list1, list2);

printf("Intersection: ");

printList(intersect);

// Find and print the union of the lists

Node* unionList = unionOfLists(list1, list2);

printf("Union: ");

printList(unionList);

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.