I need to create a default zDepthList Constructor and a zDepthList Constructor w
ID: 3863523 • Letter: I
Question
I need to create a default zDepthList Constructor and a zDepthList Constructor where the first parameter is an array and the second parameter is the length of the array. Should create a zDepthList containing all the items in the array. The items in the array are given in increasing distance to the source. The entry in the array is the index of that item in the zDepthList. The zDepthList should be a doubly linked list. The code I currently have is giving me a segmentation fault(core dumped) error when I try to run it.
class zDepthList {
typedef struct node {
int data;
node* next;
node* prev;
} Node;
private:
Node *head = NULL;
Node *tail = NULL;
public:
zDepthList();
zDepthList(int arr[], int len);
};
zDepthList :: zDepthList(){
head = NULL;
tail = NULL;
}
zDepthList :: zDepthList(int arr[], int len){
Node *temp, *ptr;
int i = 0;
while(i <= len){
temp = head;
ptr = new Node;
ptr->data = arr[i];
i++;
ptr->next = NULL;
if (head = NULL){
head = ptr;
ptr -> prev = NULL;
}
else{
while(temp != NULL){
temp = temp->next;
}
}
temp->next = tail;
ptr->prev = temp;
}
}
Explanation / Answer
A "Segmentation fault" means that you tried to access memory that you do not have access or you have not assign.
So For that in your program you have to assign memory for Node *temp, *ptr;
temp = (struct node*)malloc(sizeof(struct node));
ptr = (struct node*)malloc(sizeof(struct node));
-----------------------------------------------
class zDepthList {
typedef struct node {
int data;
node* next;
node* prev;
} Node;
private:
Node *head = NULL;
Node *tail = NULL;
public:
zDepthList();
zDepthList(int arr[], int len);
};
zDepthList :: zDepthList(){
head = NULL;
tail = NULL;
}
zDepthList :: zDepthList(int arr[], int len){
Node *temp, *ptr;
temp = (struct node*)malloc(sizeof(struct node));
ptr = (struct node*)malloc(sizeof(struct node));
int i = 0;
while(i <= len){
temp = head;
ptr = new Node;
ptr->data = arr[i];
i++;
ptr->next = NULL;
if (head = NULL){
head = ptr;
ptr -> prev = NULL;
}
else{
while(temp != NULL){
temp = temp->next;
}
}
temp->next = tail;
ptr->prev = temp;
}
}
---------------------------------------------------------------------------------------------
If you have any query, please feel free to ask.
Thanks a lot.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.