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

时间:2017-12-24 03:56:22

标签: c++ algorithm linked-list

我正在尝试将一个链接列表克隆到另一个但是我遇到了分段错误。我有一个带有两个指针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;

}

1 个答案:

答案 0 :(得分:0)

一个让我高兴的问题是,当您克隆列表时,您将克隆数据,而不是存储数据的节点。这意味着您将覆盖现有列表,而您最终得到一个自身为next引用的节点(循环链接)。

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