Answer to Question #113020 in C++ for JOYA

Question #113020
Add a destructor to the LINKLIST program. It should delete all the links when a linklist
object is destroyed. It can do this by following along the chain, deleting each link as it
goes. You can test the destructor by having it display a message each time it deletes a
link; it should delete the same number of links that were added to the list. (A destructor
is called automatically by the system for any existing objects when the program exits.)
1
Expert's answer
2020-04-30T13:37:06-0400
#include <iostream>
using namespace std;


class CustomList{
private:


	//**********************************************
	typedef struct		s_list
	{
		string 			content;
		s_list			*next;


	} 					t_list;
	//**********************************************
	t_list * _first;


public:
	CustomList(){
		_first = NULL;
	}
	//**********************************************
	void		push(string _content){
		t_list *	list = NULL;


		list = getLast();
		if (list)
			list->next = newList(_content);
		else
			_first = newList(_content);
	}
	// * * * * * * * * * * * * * * * * * * * * * * * *


	t_list * 	newList(string _content){
		t_list *newL = NULL;


		newL = new t_list;
		newL->content = _content;
		newL->next = NULL;
		cout<<"CREATE NEW LIST -> CONTENT : " <<newL->content<<endl;
		return (newL);
	}
	// * * * * * * * * * * * * * * * * * * * * * * * *
	t_list *	getLast(){
		t_list *	list = NULL;


		list = _first;
		while(list && list->next)
			list = list->next;
		return (list);
	}


	// * * * * * * * * * * * * * * * * * * * * * * * *


	~CustomList(){
		t_list *	toDel = NULL;
		while(_first){
			toDel = _first;
			cout<<"DELTETING LIST -> CONTENT : " <<toDel->content<<endl;
			_first = _first->next;
			if (toDel)
				delete toDel;
		}
	}
};
int main() {
	CustomList * customList = new CustomList();


	customList->push("fisrt list");
	customList->push("second list");
	customList->push("third list");
	cout<<"- - - - - - - - - - - - - - - - - - - - - " <<endl;
	delete customList;
	return 0;

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS