C++: Linked Lists
Posted: Sun Oct 03, 2004 4:36 pm
CURSES!!! I needed to have a way of iterating through class instances and beable to add an instance to the begining of the list and beable to remove an instance anywhere in the list...
I got this far... and it does compile.
But it crashes at line 43:
and probably other places as well if it ever got that far through the code.
If you know whats wrong with this or if you know an EASIER way of doing this kinda thing.... please inform me.
I got this far... and it does compile.
Code: Select all
#include <stdio.h>
#include <iostream.h>
//Blood - contains data for blood particles
class Blood
{
public:
//class members
float x, y;
float xvel, yvel;
int life;
//Pointer to last and next node (cell)
Blood* pLast;
Blood* pNext;
};
//Pointer to the first particle in the list
Blood* pHead = 0;
//CreateBlood - adds a new blood particle to the chain
void CreateBlood(int x, int y, int angle, int intensity)
{
//create a new instance of Blood
Blood* newnode = new Blood;
newnode->x = x; //+ rand(-3,3)
newnode->y = y;
newnode->life = 5;
//You get the picture, just convert the blitz source
//make the new node point to the head node (first one)
newnode->pNext = pHead;
cout << "pHead: " << pHead << "\n";
//since we are adding the new node to the beginning of the
//list, we set the last node pointer to 0, since there is
//no last node to point to.
newnode->pLast = 0;
//cout << "Got this far!\n";
//now we set the next node's pLast pointer to the current node
pHead->pLast = newnode;
//make the head pointer point to the new node
pHead = newnode;
return;
}
void UpdateBlood()
{
//We need to iterate through all the items in the blood
//list. So, start with a pointer pointing at the beginning
//of the linked list.
Blood* pCurrent = pHead;
//Iterate through the list until we find the last object
//in the list. This will be the one with the null next pointer.
while(pCurrent->pNext != 0)
{
//do all the stuff needed to update this particle
pCurrent->x = pCurrent->x + pCurrent->xvel;
pCurrent->life = pCurrent->life - 1;
//and so on... (this includes drawing the particle)
//TEST... display the value of the life
cout << pCurrent->life << "\n";
/*
//If the life of the particle has expired, remove it
//from the list.
if(pCurrent->life < 0)
{
//Save the pointer to the next node
Blood* next = pCurrent->pNext;
//link the last node to the next node
pCurrent->pLast->pNext = next;
//Delete the current node
delete pCurrent;
//make the next node the current node
pCurrent = next;
}
*/
}
return;
}
int number = 0;
int main(int argc, char *argv[])
{
//Test the linked list
while(1)
{
cin >> number;
if(number < 0) break;
for(int i=1; i<=number; i++)
{
CreateBlood(5,5,0,0);
}
//break;
UpdateBlood();
}
return 0;
}
Code: Select all
pHead->pLast = newnode;
If you know whats wrong with this or if you know an EASIER way of doing this kinda thing.... please inform me.