如何将一个链表插入另一个链表后面

How to insert one linked list behind another?

本文关键字:链表 插入 另一个 一个      更新时间:2023-10-16

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

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

另外,这是我使用的遍历函数,如果它有帮助的话

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

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

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

*back 未指向遍历函数中的正确节点。 它应该看起来像这样:

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