I need to create a default zDepthList Constructor and a zDepthList Constructor w
ID: 3864952 • 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 on cygwin or the grading server but runs correctly on cloud 9.
class zDepthList {
typedef struct Node { //A node for the doubly linked list
// public:
int data;
Node *previous;
Node *next;
}Node;
typedef struct List { //A special data structure that points to the head and tail nodes of the list.
// public:
Node *head;
Node *tail;
}List;
public:
zDepthList();
zDepthList(int array[], int l);
void out(const char c);
void out();
private:
List *list; //Node in the zDepthList
// int list[]; //The array which holds indices of the list
};
zDepthList :: zDepthList() { //Default constructor
list->head = 0;
list->tail = 0;
}
zDepthList :: zDepthList(int array[], int l) { //Constructor with parameters
Node *newnode;
newnode = (struct List*)malloc(sizeof(struct List));
if(l == 0)
cout << "An array cannot be made with length 'zero' " << endl;
for(int i = 0; i < l; i++) {
newnode = new Node;
newnode->data = array[i];
if(list->head == 0) { //If list is empty
list->head = newnode; //The head points to the new node
list->tail = newnode; //The tail points to the new node
newnode->previous = 0; //New node dosn't pont to anything
newnode->next = 0;
}
else {
newnode->previous = list->tail; //Since the node is on the end, the new node points to the former end node
newnode->next = 0; //new node points to nothing
list->tail->next = newnode; //The former end node points to the new node
list->tail = newnode; //The tail points to the new end of the list
}
}
}
void zDepthList :: out(const char c) { //Traverses the list, 'f' for forward, 'r' for reverse
if(c == 'f') {
Node *currnode = new Node;
currnode = list->head;
while(currnode != 0) {
cout << currnode->data << " ";
currnode = currnode->next;
}
}
if(c == 'r') {
Node *currnode = list->tail;
while(currnode != 0) {
cout << currnode->data << " ";
currnode = currnode->previous;
}
}
}
void zDepthList :: out(){
Node *currnode = new Node;
currnode = list->head;
while(currnode != 0) {
cout << currnode->data << " ";
currnode = currnode->next;
}
}
Explanation / Answer
There are errors present in this piece of code:-
1. newnode = (struct List*)malloc(sizeof(struct List)); ==> Cant convert List to node
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.