如何在另一个后面插入一个链表?

时间:2012-06-08 03:23:10

标签: c++ linked-list

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

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

* back未指向Traverse函数中的正确节点。它应该是这样的:

else if( pos > (*this).Length())
{
    alpha_numeric *k = (*this).front;
    while( k -> next != 0)
    {
        k = k -> next;
    }
    back = k;
    p = back;
}