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
using namespace std;
class Node {
public:
int data;
Node* next;

Node(int data) : data(data), next(nullptr) {}
};

class LinkedListSet {
private:
Node* head;

public:
LinkedListSet() : head(nullptr) {}

int isEmpty() const {
return head == nullptr;
}

void add(int item) {
if (!contains(item)) {
Node* new_node = new Node(item);
new_node->next = head;
head = new_node;
}
}

int remove(int item) {
Node* prev = nullptr;
Node* curr = head;

while (curr != nullptr) {
if (curr->data == item) {
if (prev == nullptr) {
head = curr->next;
} else {
prev->next = curr->next;
}
delete curr;
return 1; // Success
}
prev = curr;
curr = curr->next;
}

return 0; // Failure
}

int contains(int item) const {
Node* curr = head;
while (curr != nullptr) {
if (curr->data == item) {
return 1; // Found
}
curr = curr->next;
}
return 0; // Not found
}

void print() const {
Node* curr = head;
cout << "{";
while (curr != nullptr) {
cout << curr->data;
curr = curr->next;
if (curr != nullptr) {
cout << ", ";
}
}
cout << "}" << endl;
}

~LinkedListSet() {
Node* curr = head;
while (curr != nullptr) {
Node* temp = curr;
curr = curr->next;
delete temp;
}
}
};

int main() {
LinkedListSet set;

set.add(1);
set.add(2);
set.add(3);
set.add(4);
set.add(2); // Adding a duplicate

set.print(); // Output: {4, 3, 2, 1}

int remove_result = set.remove(3);
if (remove_result)
cout << "Item removed successfully." << endl;
else
cout << "Item not found in the set." << endl;

remove_result = set.remove(5); // Trying to remove a non-existing item
if (remove_result)
cout << "Item removed successfully." << endl;
else
cout << "Item not found in the set." << endl;

set.print(); // Output: {4, 2, 1}

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.