如何深度复制链接列表对象指针

时间:2018-09-26 04:10:06

标签: c++ oop pointers data-structures linked-list

我正在尝试创建一个函数,该函数将创建一个新的链表,并给出指向整数数组的指针。

这是我的代码,更多信息如下:

#include "iostream"


using namespace std;

//Definition for singly-linked list.
struct ListNode {

    //members
    int val;
    ListNode *next;

    //constructor
    ListNode(int x) : val(x), next(NULL) {}

    //overload assignment operator
    void operator=(const ListNode &right_list ) { 
        val = right_list.val;
        next = right_list.next;
    }   

};

//error here:
//creating new linked list
ListNode*  createNewList(int* x, int length) {
    if (*x == NULL) return NULL;
    ListNode newList = ListNode(-1);
    ListNode* ptr = &newList;
    int count = 0;
    while (count < length) {
        ptr->val = *(x + counter);
        ListNode newElement = ListNode(-1);
        ptr->next = &newElement;
        ptr = ptr->next;
        counter++;
    }
    ListNode* returnPtr = &newList;
    return returnPtr;
}

int main() {


    //create List contents
    int x [5] = {2, 4, 5, 7, 9};
    int* y = x;

    //create list: doesn't work.
    ListNode* newList = createNewList(y, 5);

    cout << "debug test: neList first val is " << newList->val << endl;

    return 0;
}

使用gdb时,我发现错误在线:

ptr-> next =&newElement;

while循环之后,列表包含元素{2,-1,-1,-1,-1}。我相信这是因为我只是将ptr-> next设置为newElement的地址,而不是创建一个与newElement相同的ListNode的新实例并将ptr-> next设置为其。

但是我想避免这种情况,并确保'='符号产生深拷贝,我只需要重载ListNode类中的赋值运算符即可。

此外,恰好在createNewList fn结束之前returnPtr-> val的值为2(我用gdb进行了验证),但是cout语句每次都会打印不同的值,因此它具有某种形式的未定义行为。我不明白原因。

如果我研究发现任何新事物,我会分享。我也可以根据要求提供更多信息。我真的很想了解指针移动的语义,因此链接到其他可能适用的情况或文章将大有帮助:)

感谢您阅读:)任何信息,我们感激不尽!

2 个答案:

答案 0 :(得分:1)

您正在堆栈上创建列表元素,因此一旦离开该功能,它们就会消失。

代替

ListNode newElement = ListNode(-1);

尝试

ListNode* newElement = new ListNode(-1);

例如

ListNode*  createNewList(int* x, int length) {
    if (x == nullptr) return x;
    ListNode* newList = new ListNode(-1);
    ListNode* ptr = newList;
    int count = 0;
    while (count < length) {
        ptr->val = *(x + counter);
        ListNode* newElement = new ListNode(-1);
        ptr->next = newElement;
        ptr = ptr->next;
        counter++;
    }
    return newList;
}

这是不必要的

int x [5] = {2, 4, 5, 7, 9};
int* y = x;

//create list: doesn't work.
ListNode* newList = createNewList(y, 5);

您可以直接直接传递x

ListNode* newList = createNewList(x, sizeof(x)/sizeof(*x));

答案 1 :(得分:0)

为什么不

std::list<int> newlist {x, x+length};
相关问题