【问题标题】:C++ writing a copy constructor for simple linked listC ++为简单链表编写复制构造函数
【发布时间】:2016-10-09 20:51:37
【问题描述】:

尝试为链表类编写一个简单的复制构造函数。我的类很简单,我有一个变量 First 指向第一个节点,还有一个变量 Last 指向最后一个节点。

它是单链接的,所以每个节点只指向下一个,没有前一个。试图写一个拷贝构造函数,但发现最后一个节点似乎仍然指向同一个地址,所以如果我在复制的列表中添加一些东西,它也会出现在原来的列表中。

这是我目前所拥有的:

queue::queue(const queue &v){
    first = v.first;
    last = v.last;


    first-> value = v.first->value;

    node *curr = first;
    node *otherCur = v.first;
    while(otherCur->next != NULL){
        cout << "------Next is: " << otherCur->next->value << endl;
        curr ->next = otherCur->next;
        curr->next->value = otherCur->next->value;
        curr = curr->next;
        otherCur = otherCur->next;

    }
    curr->next = NULL;


}

【问题讨论】:

  • 第二个对象中的所有节点都指向第一个对象中的相同节点。您需要为第二个列表的节点分配内存,然后从第一个列表的节点中复制值。
  • 重申一下,当您应该复制指向的数据时,您正在复制指针

标签: c++ linked-list copy-constructor


【解决方案1】:

您尚未在代码中进行任何node 分配。实际上每个node 应该只属于一个queue。所以通过复制v,你应该分配与v一样多的node

注意,在下面的代码中,queue 的析构函数应该删除所有创建的节点。

queue::queue(const queue &v) : first(NULL), last(NULL) {
    if (v.first) {
        first = new node(*v.first);
        first->next = NULL;
        last = first;
        // first-> value = v.first->value; // copy constructor should have done that

        node *curr = first;
        node *otherCur = v.first;
        while(otherCur->next != NULL){
            cout << "------Next is: " << otherCur->next->value << endl;
            curr->next = new node(*otherCur->next);
            curr->next->next = NULL;
            last = curr->next;
            // curr->next->value = otherCur->next->value;
            curr = curr->next;
            otherCur = otherCur->next;
        }
        // curr->next = NULL;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多