C++ This is what i have as a solution. Can you check If this makes sense according to the question if yes is there any logic errors. Are the functions doing what is said in the question. A. ~Train() { Car* current = tHead; for (int i = 0; current != NULL; i++) { Car* next = current->nextCar; delete current; current = next; } } B. void removeFirstCarOfType(const std::string& name) { if (tHead == NULL) { return; } Car* temp = tHead; if (temp->getName() == name) { tHead = temp->nextCar; free(temp); return; } int pos = 0; for (int i = 0; temp != NULL; i++) { if (temp->getName() == name) { pos = i; break; } temp = temp->nextCar; } if (temp == NULL || temp->nextCar == NULL) { return; } temp = tHead; for (int i = 0; temp != NULL && i < pos - 1; i++) { temp = temp->nextCar; } Car* nextNode = temp->nextCar->nextCar; free(temp->nextCar); temp->nextCar = nextNode; }
C++
This is what i have as a solution. Can you check If this makes sense according to the question if yes is there any logic errors. Are the functions doing what is said in the question.
A.
~Train() {
Car* current = tHead;
for (int i = 0; current != NULL; i++) {
Car* next = current->nextCar;
delete current;
current = next;
}
}
B.
void removeFirstCarOfType(const std::string& name) {
if (tHead == NULL) {
return;
}
Car* temp = tHead;
if (temp->getName() == name) {
tHead = temp->nextCar;
free(temp);
return;
}
int pos = 0;
for (int i = 0; temp != NULL; i++) {
if (temp->getName() == name) {
pos = i;
break;
}
temp = temp->nextCar;
}
if (temp == NULL || temp->nextCar == NULL) {
return;
}
temp = tHead;
for (int i = 0; temp != NULL && i < pos - 1; i++) {
temp = temp->nextCar;
}
Car* nextNode = temp->nextCar->nextCar;
free(temp->nextCar);
temp->nextCar = nextNode;
}
Step by step
Solved in 2 steps