I'm a beginner at C++ and I'm currently reading the "Jumping into C++" book. I'm currently at chapter 15 doing practice problem 1.
Practice problem 1 basically says to write a program to remove an element from a linked list; the remove function should take just the element to be removed.
Here's my code so far:
Code:
#include <iostream>
using namespace std;
struct Spaceship
{
int x;
int y;
int power;
Spaceship* pNextSpaceShip;
};
Spaceship* addNewShipToList(Spaceship* pList);
void removeShipFromList(Spaceship* pLast, Spaceship* pList);
Spaceship* pShipList;
int main()
{
pShipList = NULL;
int counter = 0;
// add 9 elements to the linked list
for(int i = 0; i < 9; ++i)
{
pShipList = addNewShipToList(pShipList);
}
// set the current to the first element in the list
Spaceship* pCurrent = pShipList;
// traverse through our list to verify how many elements are in the list
while(pCurrent != NULL)
{
pCurrent = pCurrent->pNextSpaceShip;
counter++;
}
cout << "The linked list contains " << counter << " ships" << endl;
// reset counter to 0
counter = 0;
// create a new pointer that points to the first element
Spaceship* pLast = pShipList;
// remove the first element from the list
removeShipFromList(pLast, pShipList);
// set the current to the 'new' first element of the list
pCurrent = pShipList;
// traverse through the list again to verify that one element from the list has been deleted
while(pCurrent != NULL)
{
pCurrent = pCurrent->pNextSpaceShip;
counter++;
}
cout << "The linked list contains " << counter << " ships" << endl;
cin.ignore();
cin.get();
return 0;
}
Spaceship* addNewShipToList(Spaceship* pList)
{
// to use this function, use
//list = addNewShipToList(list);
//////////////////////////////////
Spaceship* pShip = new Spaceship;
pShip->x = 0;
pShip->y = 0;
pShip->power = 20;
pShip->pNextSpaceShip = pList;
return pShip;
}
void removeShipFromList(Spaceship* pLast, Spaceship* pList)
{
pList = pList->pNextSpaceShip;
delete pLast;
}
I'm running to a run-time error when the program reaches the inside of the 2nd while-loop, specifically at line 57 which is
Code:
pCurrent = pCurrent->pNextSpaceShip;
I think the way I wrote my removeShipFromList function is wrong. Can anyone help me figure this out?
Thanks