I’ve tried, but I can’t get it to work. I need to delete an element number from a linked list. Here’s what I’ve done so far:
class MatrixLL
{
private:
struct MatrixLLElem
{
Matrix elem;
MatrixLLElem* next;
MatrixLLElem(const Matrix& m1): elem(m1), next(NULL)
{ }
};
MatrixLLElem* start;
public:
MatrixLL();
Matrix& elem(const int index);
int getlength();
void append(const Matrix& m1);
void deleteelem(const int index);
~MatrixLL();
};
My other code is of no concern, as it works perfectly, so here’s the code for the deleteelem(); function:
void MatrixLL::deleteelem(const int index)
{
if(index < 1)
throw "Invalid index specified.";
if(start == NULL)
throw "No element at specified location.";
MatrixLLElem* currP = start;
MatrixLLElem** prevP = NULL;
for(int i = 1; i < index; i++)
{
prevP = &currP;
if((*currP).next != NULL)
currP = (*currP).next;
else
throw "No element at specified location.";
}
if(prevP == NULL)
{
start = NULL;
}
else
{
(*prevP) = (*currP).next;
}
delete currP;
}
EDIT: It reduces the length from 2 to 0 if I check… And the length function seems to be working fine if I append and then check etc. The index is supposed to start from 1.
The problem is when you want to delete the first element (index=1).
instead of
the correct one is: