Linked list deep copy constructor

夙愿已清 提交于 2019-12-13 06:33:53

问题


I am implementing a linked list class' copy constructor which will make a deep copy. This is the code that i have:

List( const List & rhs ) {
        Node* rhsFront = rhs.header->next;
        Node* prev = header;
        while (rhsFront) {
            prev->next = new Node(rhsFront->data, nullptr);
            rhsFront = rhsFront->next;
            prev = prev->next;
        }
}

However, it crashes at this line:

prev->next = new Node(rhsFront->data, nullptr);

What did I do wrong?


回答1:


Node* prev = header;

I would guess the header there not to be initialised, thus causing the prev->next to be a random pointer (most likely something like 0) and trying to write to that point crashes the program. If so, this might work.

List( const List & rhs ) {
    Node* rhsFront = rhs.header->next;
    header = new Node(rhs.header->data, nullptr);
    Node* prev = header;
    while (rhsFront) {
        prev->next = new Node(rhsFront->data, nullptr);
        rhsFront = rhsFront->next;
        prev = prev->next;
    }
}



回答2:


Why are you starting at next and not header. Node* prev = header; where is header defined? Have you already allocated the memory needed? instead start from header and copy over.

List( const List & rhs ) {
    Node* rhsFront = rhs.header;
    Node* prev = header;
    while (rhsFront) {
        prev = new Node(rhsFront->data, rhsFront->next);
        rhsFront = rhsFront->next;
        prev = prev->next;
    }
}

This way you are copying all nodes and not skipping the header. Hope this makes sense. Also the actual exception you are getting might give a clue as to which access is NPE.



来源:https://stackoverflow.com/questions/40320856/linked-list-deep-copy-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!