C++ Problem: I am trying to delete a node from a doubly linked list in a C++ pro
ID: 3589676 • Letter: C
Question
C++ Problem:
I am trying to delete a node from a doubly linked list in a C++ program. The function is passed a head pointer and a city name. It is supposed to search the linked list and delete the node with the city name that matches the passed cityName string. It is then supposed to reconnect the list after deleting the desired node. This is where I think I am making a mistake. Also, if the node doesn't exist or the list is empty, it prints out a statement "City does not exist." Please help me slove this problem! Below is my code thus far and I have inculded my Code Runner failed test case. Also included is my city structure. You may NOT change the structure!
Test Cases:
//DO NOT MODIFY THIS STRUCT struct city string name; // name of the city city *next; /I pointer to the next city int numberMessages; // how many messages passed th string message; // message we are sending accross rough this cityExplanation / Answer
city* deleteCity(city *head, string cityName){
city *currentCity = new city;
currentCity = head;
city *previousCity = new city;
previousCity = head;
bool flag = true; // No need of this flag actually
if (head == NULL){
cout << "List is empty ";
return head;
}
while (currentCity != NULL && currentCity->name != cityName){
previousCity = currentCity;
currentCity = currentCity->next;
}
if (currentCity == NULL){
cout << "City does not exist" << endl;
}
if (currentCity == head){
head = currentCity->next;
delete currentCity;
}
else {
previousCity->next = currentCity->next;
delete currentCity;
}
return head;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.