I need help answering this qustion: struct Node { InfoType info; Node * next; No
ID: 3593293 • Letter: I
Question
I need help answering this qustion:
struct Node
{
InfoType info;
Node * next;
Node ( InfoType x, Node *p = NULL ) { info = x; next = p; }
};
Node * list;
(14) 8. Using the declarations, write C++ code segments
to (make sure to free any storage that is deleted):
A. Add val (of InfoType) to the front of the linked list pointed to by list.
B. Remove the front node of the linked list pointed to by list. If the list is empty, do nothing.
C. Remove the second node in the list pointed to by list. If there are less than two nodes, do nothing.
D. Add val (of InfoType) to the end of the linked list pointed to by list. Handle the empty list case!
Explanation / Answer
struct Node
{
InfoType info;
Node * next;
Node ( InfoType x, Node *p = NULL ) { info = x; next = p; }
};
Node *list;
void add(InfoType data) {
list = new Node(data, list);
}
InfoType remove() {
if (list == NULL)
return NULL;
Node tmp = list;
InfoType data = tmp -> info;
list = list->next;
delete tmp;
return data;
}
InfoType removeSecond() {
if (list == NULL)
return NULL;
if (list->next == NULL)
return NULL;
Node tmp = list->next;
InfoType data = tmp -> info;
list->next = list->next->next;
delete tmp;
return data;
}
void addLast(InfoType data) {
if (list == NULL)
list = new Node(data, list);
else {
Node tmp = list;
while(tmp->next != NULL);
tmp = tmp->next;
tmp->next = new Node(data);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.