For an assignment, I need to add one objects linked list to the back of another. I have this:
WORD you("you");//where you's linked list now contains y o u
WORD are("are");//where are's linked list now contains a r e
and I want to do this:
you.Insert(are,543);//(anything greater they the current objects length is
//attached to the back. So that 543 can be anything > you's length
so Now, you’s linked linked list should contain:
y o u a r e
I was able to insert in the front, and anywhere in between the letters, but when I try to insert in the back the program crashes instantly. Can someone please help me figure out what is wrong? I tried using the debugger and it points to one line, but I cant figure out what is wrong. I’ve marked the line as a coming in the function:
void WORD::Insert(WORD & w, int pos)
{
if(!w.IsEmpty())
{
alpha_numeric *r = w.Cpy();
alpha_numeric *loc;
(*this).Traverse(loc,pos);//pasing Traverse a pointer to a node and the position in the list
//if(loc == 0)
//{
// alpha_numeric *k = r;//k is pointing to the begin. of the copied words list
// while(k -> next != 0)
// {
// k = k -> next;//k goes to the back
// }
// k -> next = front;//k(the back) is now the front of *this
// front = r;//front now points to r, the copy
//}
else if(loc == back)
{
back -> next = r; //<<<-------DEBUGGER SAYS ERROR HERE?
length += w.Length();
while(back -> next!= 0)
{
back = back -> next;
}
}
/*else
{
alpha_numeric *l = r;
while(l -> next != 0)
{
l = l -> next;
}
l -> next = loc -> next;
loc -> next = r;
}
length += w.Length();
}*/
}
Also, here is the Traverse function I used if it helps
void WORD::Traverse(alpha_numeric * & p, const int & pos)
{
if(pos <= 1)
{
p = 0;
}
else if( pos > (*this).Length())
{
p = back;
}
else
{
p = front;
for(int i = 1; i < pos - 1; i++)
{
p = p -> next;
}
}
}
I DECLARED BACK AS A POINTER IN THE PRIVATE SECTION OF THE CLASS. *back
This is how I put it in the constructor
WORD::WORD()
{
alpha_numeric *p;
front = new alpha_numeric;
front = 0;
length = 0;
back = front;
for(p = front; p != 0; p = p -> next)
{
back = back -> next;
}
}
*back is not pointing to the correct node in the Traverse function. It should look like this: