I'm implementing DLL Class. But I can't figure out why calling my constructor always fail.
class Node {
public:
Node();
Node(int value, Node *next, Node *prev);
~Node();
int value;
Node *next;
Node *prev;
};
Node::Node() {
this->value = 0;
this->next = NULL;
this->prev = NULL;
}
Node::Node(int value, Node *next, Node *prev) {
this->value = value;
this->next = next;
this->prev = prev;
}
class DLLStructure {
public:
DLLStructure();
DLLStructure(int *arr, int size);
~DLLStructure();
private:
Node *first;
Node *last;
};
DLLStructure::DLLStructure(int arr[], int size) {
Node *first = NULL;
Node *last;
Node *prev;
for (int i = 0; i < size; i++) {
//initialize the current node
last = new Node(arr[i], NULL, NULL);
if (!first) {
first = last;
prev = last;
continue;
}
prev->next = last;
last->prev = prev;
prev = last;
}
this->first = first;
this->last = last;
}
int main(){
int arr[5] = {1,1,1,1,1};
DLLStructure dll(arr, 5);
return 0;
}
The weird thing is when I comment out first = last
in the if block in DLL Constructor , the program returns zero but when I try to print the value of the list, it's again segmentation fault.
The bug is in my destructor. I mistakenly make Node *cur
pointing to null and call cur->prev
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.