I have been having a few problems recently while getting to grips with a template circular linked list for learning purposes. Sometimes when I try to delete from the first node in the list, it will either delete that node or delete that and the node after it or the program crashes.
Every other item in the list I am successful in deleting including the last.
For example,
Apple <- Pear
Orange Banana
Pear
Banana
Another problem is if I delete Banana first and then apple thereafter the program will crash and I will get this error,
Exception thrown: read access violation.
std::_String_alloc<std::_String_base_types<char,std::allocator<char> > >::_Mysize(...) returned 0xFFFFFFFFFFFFFFFF.
I will attach the code for the creation of the linked list node and deletion
I am thinking there is a problem with the deletion function but I have no idea what. If anyone could share some insight into this it would be much appreciated,
> if (first == NULL)
I'll recommend you to create a list with an empty header cell.
1 2 3 4 5 6
class list{
node header; //note that it's not a pointer
list(){
header.link = &header; //points to itsef
}
};
that way all your pointers would always be valid/dereferenceable.
> I will attach the code for the creation of the linked list node and deletion
I want to simply run your program through a debugger.
Then may focus on what to read.
template <class Type>
class LinkedListType
{
public:
void initializeList();
//Initialize the list to an empty state.
//Postcondition: first = NULL, last = NULL, count = 0;
1 2 3 4 5 6 7
protected:
int count; //variable to store the number of list elements
//
nodeType<Type> *first; //pointer to the first node of the list
nodeType<Type> *last; //pointer to the last node of the list
nodeType<Type> header; // dummy node <-------
I am unsure of how to implement what you suggested, add the dummy header in the ADT class members along with first and last and also the header.link = &header;
You don't need the case at lines 22-27. When deleting the first node, the only special case is when it's the only node. If there are multiple nodes and you're deleting the first then the last doesn't change. So lines 22-24 should be:
1 2 3
} else {
first = first->link;
}
Line 44: since it's a circular list, current will never be NULL. This should be while (trailCurrent != last && !found)
Line 57 is wrong. If you're deleting the last node then you want to do: last = trailCurrent;
This is untested, but I think you can combine all of this like so: