Question: 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.

  1. Can my implementation be further improved?
  2. 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)
  3. 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

#include class 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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!