Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

language:c++ Explain why deleting the LinkedList object l does not work as desir

ID: 662825 • Letter: L

Question

language:c++

Explain why deleting the LinkedList object l does not work as desired (de-allocating all memory associated with the list) for our linked list implementation.

class LinkedList{          
  
public:
   LinkedList();           // default constructor; creates a "blank" linked list element
   void add(double val);   // fills the value field of the last element of the chain, and adds a new (blank) element to the end of the chain
   void print();           // prints value stored in all elements of the chain from this element on except for the last element, which is blank
  
private:
   LinkedList* getLast();   // returns a pointer to the last element of the chain
   double value;           // value stored in this element
   LinkedList* p;           // pointer to the next element of the chain

};

LinkedList::LinkedList(){
   value=0;
   p=NULL;
}

LinkedList* LinkedList::getLast(){
   LinkedList* current=this;
   while(current->p!=NULL)
current=current->p;
   return current;
}

void LinkedList::add(double val){
   LinkedList*current=getLast();
   current->value=val;
   current->p=new LinkedList;
}

void LinkedList::print(){
   LinkedList*elementToPrint=this;
   if(elementToPrint==NULL){
       return;
   }
   while(elementToPrint->p!=NULL){
       cout        elementToPrint=elementToPrint->p;
}
}

int main(){
LinkedList l = LinkedList();
   l.add(10);
   l.add(12);
   l.add(15);
   l.add(17);
   l.add(18);
  
   cout << "The values stored are: " << endl;
   l.print();
}

Explanation / Answer

whenever you are deleting a particular objects. the memory space of the object will get deleted