# Thread: Chapter 15 - Practice Problem1

1. ## Chapter 15 - Practice Problem1

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;
};

void removeShipFromList(Spaceship* pLast, Spaceship* pList);

Spaceship* pShipList;

int main()
{
pShipList = NULL;

int counter = 0;
for(int i = 0; i < 9; ++i)
{
}

// 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;
}

{
// to use this function, use
//////////////////////////////////
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

2. Removing a node from a linked list using only the node to delete as a starting point requires that the list be doubly linked. Then you can do these four lines:

Code:
```if (old->next != NULL )
old->next->prev = old->prev;
if (old->prev != NULL )
old->prev->next = old->next;```
Now as far as the list is concerned, old isn't in there. You can free old's memory.

3. I'm a little surprised that "Jumping Into C++" does not introduce classes earlier in the book. I just looked at the table of contents, and it appears that it discusses lists and trees before it talks about classes. this seems backwards to me, and this code in particular seems very C-style.