The following code is a linked list that adds a new node to the end of the list.
ID: 3834820 • Letter: T
Question
The following code is a linked list that adds a new node to the end of the list. Select the appropriate program that would change it to a double linked list (a list where each node points to the next as well as the previous node).
struct Node {
int x, y;
Node *next;
};
Node *head, *tail;
void add(int newx, int newy) {
Node *newentry = new Node;
newentry->x = newx;
newentry->y = newy;
newentry->next = NULL;
if (head == NULL) {
head = tail = newentry;
}
else {
tail->next = newentry;
tail = newentry;
}
}
A.)
/****************************************************************/
struct Node {
int x, y;
Node *prev, *next;
};
Node *head, *tail;
void add(int newx, int newy) {
Node *newentry = new Node;
newentry->x = newx;
newentry->y = newy;
newentry->next = NULL;
newentry->prev = NULL;
if (head == NULL) {
head = tail = newentry;
}
else {
tail->next = newentry;
tail = newentry;
newentry->prev = tail;
}
}
B.)
/****************************************************************/
struct Node {
int x, y;
Node *prev, *next;
};
Node *head, *tail;
void add(int newx, int newy) {
Node *newentry = new Node;
newentry->x = newx;
newentry->y = newy;
newentry->next = NULL;
if (head == NULL) {
head = tail = newentry;
newentry->prev = NULL;
}
else {
tail->next = newentry;
newentry->prev = tail;
tail = newentry;
}
}
C.)
/****************************************************************/
struct Node {
int x, y;
Node *prev, *next;
};
Node *head, *tail;
void add(int newx, int newy) {
Node *newentry = new Node;
newentry->x = newx;
newentry->y = newy;
newentry->next = NULL;
if (head == NULL) {
head = tail = newentry;
}
else {
tail->next = newentry;
newentry->prev = tail;
tail = newentry;
}
}
Explanation / Answer
B is correct. Reason
In A , the else part is incorrect:
tail->next = newentry;
tail = newentry;
newentry->prev = tail;
here once the tail = newentry and then newentry->prev = tail, means prev points to itself which is incorrect.
In C, in case of head==NULL, we are not setting the newentry->prev = NULL which is important.
thus B is correct.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.