【问题标题】:Linked list copy constructor C++链表复制构造函数 C++
【发布时间】:2013-10-14 04:42:11
【问题描述】:

我真的很困惑为什么这个复制构造函数不起作用!我正在创建一个iter 指针,它指向与head 相同的ListNode,但是当我将内容从s 复制到it 时,headiter 没有连接!

换句话说,当打印头时,只有第一个字符在那里,但如果我要遍历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;
            }
        }
    }
}

【问题讨论】:

  • NumAllocations 是内置类型吗?因为它似乎没有在任何地方初始化。
  • Sorry yes NumAllocations 是 Mystring.h 中定义的全局变量

标签: c++ pointers memory-management linked-list copy-constructor


【解决方案1】:

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

试试这个。

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的附件。你只是在创建一个新节点,并没有对它做任何事情。

【讨论】:

  • 哦哇哦..这是一个愚蠢的错误,我发誓我检查了 100 次,似乎它们都连接了!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多