When I attempt to delete a certain element from a linked list, some of the elements end up somehow obtaining random values in place of their originals. I don't understand why this is happening. Can someone help me please? Here is my code:
void removeSpaceShipPower(SpaceShip *x, int y)
{
SpaceShip *current = x;
SpaceShip *toDelete = NULL;
SpaceShip *next = NULL;
while(current != NULL)
{
if(current->nextShip->power == y)
{
next = current->nextShip->nextShip;
current->nextShip = next;
toDelete = current->nextShip;
free(toDelete);
return;
}
current = current->nextShip;
}
}
And then main:
int main()
{
SpaceShip *freeList = new SpaceShip;
freeList->power = 50;
freeList->health = 100;
SpaceShip *freeList2 = new SpaceShip;
freeList2->power = 25;
freeList2->health = 100;
SpaceShip *freeList3 = new SpaceShip;
freeList3->power = 75;
freeList3->health = 100;
SpaceShip *freeList4 = new SpaceShip;
freeList4->power = 100;
freeList4->health = 100;
freeList->nextShip = freeList2;
freeList2->nextShip = freeList3;
freeList3->nextShip = freeList4;
freeList4->nextShip = NULL;
printSpaceShip(freeList);
cout << getLowestPower(freeList) << endl;
removeSpaceShipPower(freeList, 75);
printSpaceShip(freeList);
}
And then the output is:
C:\Users\Russell\Desktop\C++ Programs>a
Spaceship #1 Power: 50 Health: 100
Spaceship #2 Power: 25 Health: 100
Spaceship #3 Power: 75 Health: 100
Spaceship #4 Power: 100 Health: 100
25
Spaceship #1 Power: 50 Health: 100
Spaceship #2 Power: 25 Health: 100
Spaceship #3 Power: 9310088 Health: 9306304
Aucun commentaire:
Enregistrer un commentaire