Good evening. I've recently had an assignment to create a doubly linked list that is self contained. This means that the entire list is contained in a single class - the class acts as both the list and the node.

I've completed everything and have gotten to my final task and that is coding the function that will destroy the entire list. However I'm having issues visualising it. I've already coded a destructor that removes a node from the list, and just need it to function on the entire list. That being said, I also need the list to delete itself afterwards seeing as it was assigned in main() with new. When I attempted to

delete this;

at the end of the function. I received errors at runtime.

Following is an example of my destructor function:

~ListNode()
	{
		//Guarding if statement.
		if(mPrev && mNext)
		{
			mPrev->mNext = Next();
			mNext->mPrev = Previous();
		}
	}

Any assistance would be much appreciated!

Recommended Answers

All 3 Replies

You should be able to call the destructor which should call delete of the variable that points to the next node.

I get a debug assertion error when I attempt to do that.

Managed to solve my own problem. This is how I destroyed my entire list. Since it's self contained this suits my purposes. I then deleted in main() to get rid of the main pointer since you are unable to delete *this.

void DestroyList()
	{
		ListNode *iter = this, *temp;

		while(iter != NULL) //while the list is not empty
		{
			temp = iter; //store the current node.
			iter = iter->next; //visit the next node
			
			if(temp->prev)
				temp->prev = NULL;
			if(temp->next)
				temp->next = NULL;
		}
	}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.