克隆链接列表会导致分段错误

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了克隆链接列表会导致分段错误相关的知识,希望对你有一定的参考价值。

我试图克隆一个链表到另一个,但我得到分段错误。我有一个带有两个指针m_Nextm_Bak的结构,我有一个存储名称的字符指针。我想用C ++做。我需要克隆src并返回一个克隆的链表。

TEMPLOYEE        * cloneList    ( TEMPLOYEE       * src ) {

    TEMPLOYEE* curr = src, *temp;

    while (curr) {
        temp = curr->m_Next;
        temp->m_Name = new char[strlen(curr->m_Name) + 1];
        strcpy ( temp->m_Name, curr->m_Name);
        curr->m_Next->m_Next = temp;
        curr = temp;
    }

    curr = src;

    while (curr) {
        curr->m_Next->m_Bak = curr->m_Bak->m_Next;

        curr = curr->m_Next?curr->m_Next->m_Next:curr->m_Next;
    }

    TEMPLOYEE* original = src, *copy = src->m_Next;

    temp = copy;

    while (original && copy)
    {
        original->m_Next =
                original->m_Next? original->m_Next->m_Next : original->m_Next;

        copy->m_Next = copy->m_Next?copy->m_Next->m_Next:copy->m_Next;
        original = original->m_Next;
        copy = copy->m_Next;
    }

    return temp;
  }

编辑:

我遇到了问题所在。

TEMPLOYEE        * cloneList    ( TEMPLOYEE       * src ) {
    if(!src) return NULL;
    TEmployee * current = src;

    while(current){
        TEmployee * current_next = current->m_Next;
        current->m_Next  =  newEmployee(current->m_Name,current->m_Next);
        current->m_Next->m_Next = current_next;
        current = current_next;
    }
    current = src;

    TEmployee * clone_head  = current->m_Next;

    while(current){
        TEmployee * clone = current->m_Next;
        if(current->m_Bak){
            clone->m_Bak    = current->m_Bak->m_Next;
        }
        current = clone->m_Next;
    }

    current = src;

    while(current){
        TEmployee * clone  = current->m_Next;
        current->m_Next = clone->m_Next;
        if(clone->m_Next){
            clone->m_Next = clone->m_Next->m_Next;
        }
        current = current->m_Next;
    }
    return clone_head;

}
答案

我突出的一个问题是,当您克隆列表时,您将克隆数据,而不是存储数据的节点。这意味着您将覆盖现有列表,最终得到的节点本身作为next参考(循环链接)。

因此,当您克隆列表时,除了复制数据外,还需要分配新的TEMPLOYEE节点(到temp中)。不要忘记记住您分配的第一个(新的克隆列表的头部)返回给调用者。

以上是关于克隆链接列表会导致分段错误的主要内容,如果未能解决你的问题,请参考以下文章

将文本文件解析为列表会导致分段错误

为啥释放内存会导致分段错误?

为啥此代码会导致分段错误错误?

什么会导致 C++ 中的分段错误? [关闭]

为啥这个字符串反转 C 代码会导致分段错误? [复制]

C即使分配了内存,修改链表的程序也会导致分段错误