Hi, I am trying to learn c++ by my own using the Jumping into c++ book. So, im at the linked list part and I am trying to write a program which add and remove element from a linked list.
So, my add an element function work perfectly but there is a problem with my delete function. When I delete the first element of the list two times in a row the program crash and I dunno why.
I use this statement to know I am pointing at the first element in the list. If p_ship->p_last_enemy is null. Then I know it is the first element of the list. I use here in the delete an element function :
In the same way that addNewEnemyToList can result in a new list "head", so can delete_spaceship.
I suspect that's why you tell us that delete_spaceship is supposed to return a pointer to an EnemySpaceShip. It is too bad you don't follow up on that promise and return a pointer.
EnemySpaceShip* delete_spaceship(string name, EnemySpaceShip* p_list)
{
EnemySpaceShip* current = p_list;
while (current && current->ship_name != name)
current = current->p_next_enemy;
if (current)
{
if (current == p_list)
p_list = current->p_next_enemy;
else
current->p_last_enemy->p_next_enemy = current->p_next_enemy;
if (current->p_next_enemy)
current->p_next_enemy->p_last_enemy = current->p_last_enemy;
delete current;
}
return p_list;
}
// Meanwhile, in main...
while (1)
{
cout << "Do yo wish to delete an enemy space ship?" << endl;
cin >> yesorno;
if (yesorno == "no")
break;
else
{
if (p_enemies)
{
cout << "What is the name of the enemy space ship you want to be deleted?" << endl;
cin >> name;
p_enemies = delete_spaceship(name, p_enemies);
display_list(p_enemies);
}
else
cout << "The list is empty.\n";
}
}