问题
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