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 <iostream>

using namespace std;

// define a linked list node for set

struct SetNode {

int data;

SetNode* next;

};

// define the Set class using a linked list

class Set {

private:

SetNode* head;

int size;

public:

Set() {

head = NULL;

size = 0;

}

void add(int value) {

// check if value already exists in set

SetNode* node = head;

while (node != NULL) {

if (node->data == value) {

return;

}

node = node->next;

}

// value does not exist, so add it to the set

SetNode* new_node = new SetNode;

new_node->data = value;

new_node->next = head;

head = new_node;

size++;

}

void remove(int value) {

// check if value exists in set

SetNode* node = head;

SetNode* prev = NULL;

while (node != NULL) {

if (node->data == value) {

break;

}

prev = node;

node = node->next;

}

if (node == NULL) {

return;

}

// value exists, so remove it from the set

if (prev == NULL) {

head = node->next;

} else {

prev->next = node->next;

}

delete node;

size--;

}

void display() {

SetNode* node = head;

cout << "{";

while (node != NULL) {

cout << node->data;

node = node->next;

if (node != NULL) {

cout << ", ";

}

}

cout << "}" << endl;

}

int get_size() {

return size;

}

bool contains(int value) {

SetNode* node = head;

while (node != NULL) {

if (node->data == value) {

return true;

}

node = node->next;

}

return false;

}

Set union_with(Set other_set) {

Set result_set;

SetNode* node = head;

while (node != NULL) {

result_set.add(node->data);

node = node->next;

}

node = other_set.head;

while (node != NULL) {

result_set.add(node->data);

node = node->next;

}

return result_set;

}

Set intersection_with(Set other_set) {

Set result_set;

SetNode* node = head;

while (node != NULL) {

if (other_set.contains(node->data)) {

result_set.add(node->data);

}

node = node->next;

}

return result_set;

}

};

int main() {

Set set1;

set1.add(1);

set1.add(2);

set1.add(3);

set1.add(4);

Set set2;

set2.add(3);

set2.add(4);

set2.add(5);

set2.add(6);

Set set3 = set1.union_with(set2);

Set set4 = set1.intersection_with(set2);

cout << "Set 1: ";

set1.display();

cout << "Set 2: ";

set2.display();

cout << "Union of Set 1 and

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.