Problem in LinkedList destructor.
Hello to all,
I have write following LinkedList destructor, but there is one problem in it. I want to know, is this a valid LinkedList destructor?
Code:
LinkedList::~LinkedList()
{
ListNode *ptrs;
for (ptrs = heads; heads; ptrs = heads)
{
heads = heads->next
delete ptrs;
}
}
I don't know whether it is right or not. Can anyone tell me what is problem in LinkedList destructor?
Please help me.
Re: Problem in LinkedList destructor.
You have to use while-loop instead of for loop to fix this problem. It is very simple to use. I have written following code to you. Just try to understand it.
Code:
ListNodes* currents = heads;
while( currents != 0 ) {
ListNodes* nexts = currents->next;
delete currents;
currents = next;
}
head = 0;
In the above code I have use one variable to linked list value.
Re: Problem in LinkedList destructor.
Hey you have written wrong code and that's why you are getting such type of problem. I have written following code for you. It is working program. In the following code I have use ~CLists() to define destructor. I also have use pPointers = pRoots; to sets the pointer to start at the beginning of the list.
Code:
CLists::~CLists() // destructor
{
CNode *pPointers;
pPointers = pRoots;
do
{
CNodes *pPointersDels;
pPointersDels = pPointers;
delete pPointerDels;
if(pPointers->pNexts != 0)
{
pPointers = pPointers->pNexts;
}
} while(pPointers != pHead);
}
Re: Problem in LinkedList destructor.
As per my information you have to use if-else statement instead of for statement to fix this problem. I have written following destructor program using if-else statement. Just try to understand it.
Code:
CLists::~CLists() // destructor
{
do
{
CNodes *pPointers;
pPointers = pRoots;
if(pRoots->pNexts == 0)
{
delete pRoots->pNexts;
delete pRoots;
delete pPointers;
}
else
{
pRoots = pRoots->pNext;
delete pPointers;
}
} while(pRoots);
Re: Problem in LinkedList destructor.
You have to use condition "head;" to check that it is not null. As per my information "head" is same as "head != null". You have write wrong code and that's why you are getting such type of problem. You have unnecessarily used for statement and that's why you are getting such type of problem. You have to use standard library to fix this problem.
Re: Problem in LinkedList destructor.
You have to first use following code in your program to fix this problem. It is very simple one.
Code:
heads(32) -> [54]singles_nodes -> [0]ends-ofs-lists.
After this try to run following code
for (ptrs = heads; headss != 0; ptr = head)