当我尝试运行复制构造函数时,为什么会出现“分段错误”?

问题描述

复制函数在我退出函数时执行,然后打印循环链表的当前内容。我想要做的是让一个名为 other 的对象在删除之前指向原始列表(这是程序退出之前的原始列表)。然后我将原始列表中的数据分配到新列表的节点中。由于第一个或头节点是最大的,我使用 while ( p->info != p->next->info ) 作为条件复制节点之前的所有内容,然后 if (p->info == other .first->info) 来标识头节点,然后使该节点的数据或信息等于复制列表的节点的头。

'''

//复制构造函数

  template <class T>
    void CLList<T> :: copy ( const CLList<T> & other )
    {
       if ( other.first == NULL )
     first = NULL;
   else
   {
  first = new node<T>;
  first->info = other.first->info;

  node<T> *p = other.first->next;
  node<T> *r = first;

  
  while ( p->info != p->next->info )
  {
      r->next = new node<T>;
      r->next->info = p->info;
   if (p->info == other.first->info)
  {
    r->next = new node<T>;
    r->next->info = other.first->info;
  }


// Node 
 template <class T>
  struct node
{
    T info;
     node *next; 
  };

解决方法

这段代码对于复制构造函数来说都是错误的。 while 循环实际上根本没有迭代输入列表,它只是一遍又一遍地复制第一个节点。此外,循环根本不应该比较 info 值。

这段代码需要完全重写。试试更像这样的东西:

template <class T>
CLList<T>::CCList(const CLList<T> &other)
    : first(NULL)
{
    node<T> *p = other.first;
    node<T> **r = &first;

    while (p)
    {
        *r = new node<T>;
        (*r)->info = p->info;
        (*r)->next = NULL;
        r = &((*r)->next);
        p = p->next;

        // for a circular list only:
        if (p == other.first) break;
    }

    // for a circular list only:
    if (r != &first) *r = first;
}