0

对于作业,我需要将一个对象链表添加到另一个对象的后面。我有这个:

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

我想这样做:

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

所以现在,你的链表应该包含:

y o u a r e

我可以在前面插入,也可以在字母之间的任何地方插入,但是当我尝试在后面插入时,程序会立即崩溃。有人可以帮我找出问题所在吗?我尝试使用调试器,它指向一行,但我不知道出了什么问题。我已将该行标记为函数中的传入:

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();
}*/
}

另外,如果有帮助,这是我使用的 Traverse 功能

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;
    }
}

}

我在班级的私人部分宣布回来作为指针。*背部

这就是我把它放在构造函数中的方式

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;
}
}
4

2 回答 2

0

我强烈怀疑您的问题源于列表为空时未back在块中更新。if(loc==0)

在这种情况下,back会留下== 0,并且追加操作会失败。

于 2012-06-08T03:44:10.537 回答
0

*back 没有指向 Traverse 函数中的正确节点。它应该如下所示:

else if( pos > (*this).Length())
{
    alpha_numeric *k = (*this).front;
    while( k -> next != 0)
    {
        k = k -> next;
    }
    back = k;
    p = back;
}
于 2012-06-08T04:26:47.870 回答