1

我真的很困惑,为什么这个拷贝构造函数不工作!我正在创建一个指向与head相同的ListNode的iter指针,但是当我将s中的内容复制到it,headiter未连接!链接列表复制构造函数C++

换句话说,当打印头时,只有第一个字符在那里,但如果我要遍历iter,列表的其余部分就在那里。 为什么不是iterhead指向相同的对象?!

注意:这是一个链接列表被用来实现一个名为MyString的类。

struct ListNode { 
    char info; 
    ListNode *next; 
    ListNode() : info('0'), next(0) {} 
    ListNode (char c) : info (c), next(0) {} 
}; 

class MyString { 
    private: 
    ListNode *head; 

    MyString::MyString(const MyString & s) { 
     if (s.head == 0) 
      head = 0; 
     else { 
      head = new ListNode (s.head -> info); 
      ++NumAllocations; 
      ListNode *iter = head; 
      for (ListNode *ptr = s.head -> next; ptr != 0; ptr = ptr ->next) { 
       iter = iter -> next; 
       iter = new ListNode (ptr -> info); 
       ++NumAllocations; 
      } 
     } 
    } 
} 
+0

是内置类型的'NumAllocations'?因为它似乎没有在任何地方初始化。 – juanchopanza

+0

对不起是NumAllocations是Mystring.h中定义的一个全局变量 – Tangleman

回答

3

您似乎没有将该列表附加到任何地方的头部。

试试这个。

MyString::MyString(const MyString & s) { 
    if (s.head == 0) 
     head = 0; 
    else { 
     head = new ListNode (s.head -> info); 
     ++ NumAllocations; 
     ListNode *iter = head; 
     for (ListNode *ptr = s.head -> next; ptr != 0; ptr = ptr ->next) { 
      iter -> next = new ListNode (ptr -> info); 
      iter = iter -> next; 
      ++ NumAllocations; 
     } 
     printList(head); 
    } 
} 

请注意iter-> next的附件。你只是创建一个新的节点而不做任何事情。

+1

哦哇..这是一个愚蠢的错误,我发誓我检查了它100次,似乎他们都连接!谢谢! – Tangleman