Answered step by step
Verified Expert Solution
Question
1 Approved Answer
I am building two simple classes int LinkedList with only 4 methods and a subclass int ChildList which inherits from LinkedList with only one extra
I am building two simple classes int LinkedList with only 4 methods and a subclass int ChildList which inherits from LinkedList with only one extra method contain.
- Can my implementation be further improved?
- What error handling can I incorporate in my design? For instance in my 'push' method what scenarios can it return false (false meaning you cannot add anymore to the list)
- Given that there is no size constraint for this list, can it run out of memory? How to I handle that error in my program especially for the memory being allocated with 'new'?
Main.cpp
#include#include #include "LinkedList.h" #include "ChildList.h" using namespace std; int main(){ ChildList cList; for (int i = 0; i < 1000; i++) cList.push(i); cout<< cList.contains(699) << endl; cout << cList.getSize() << endl; }
LinkedList.h
#includeclass Node { public: int data; Node* next; Node(int ndata = 0){ data = ndata; next = nullptr; } }; class LinkedList{ protected: int size; Node* front; public: LinkedList(); ~LinkedList(); virtual int getSize() const; virtual bool empty() const; virtual bool push(int ndata); virtual void clear(); };
LinkedList.cpp
#include "LinkedList.h" LinkedList::LinkedList(){ size = 0; front = new Node(-1); } LinkedList::~LinkedList(){ clear(); } int LinkedList::getSize() const{ return size; } bool LinkedList::empty() const{ return size == 0; } bool LinkedList::push(int ndata){ // What types of error can I check for? Node* newNode = new Node(ndata); newNode->next = front->next; front->next = newNode; size++; return true; } void LinkedList::clear(){ if (getSize() == 0){ return; }else{ Node* temp1 = front; while (temp != nullptr){ Node* temp2 = temp1->next; delete temp1; temp1 = temp2; } } size = 0; }
ChildList.h
#pragma once #include "LinkedList.h" class ChildList : public LinkedList { public: ChildList(); ~ChildList(); bool contains(int data) override; };
ChildList.cpp
#include "ChildList.h" ChildList :: ChildList(){ } ChildList :: ~ChildList(){ clear(); size = 0; } bool ChildList::contains(int data){ if (getSize() == 0) { return false; }else{ Node* temp = front->next; while (temp != nullptr){ if (temp->data == data){ return true; } temp = temp->next; } } return false; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started