Another way I've seen people do it is by recursing in the destructor: ~Node() { if (next != null) delete next; }
Of course, if you'd ever want to delete a single item, you'll end up deleting everything behind it as well.
Don't define a struct (or anything, for that matter) inside a function. Move your struct definition outside of main(). Usually you'll even want to put it in a separate file.
#include <stdlib.h>
#include <iostream>
#include <ctime>
usingnamespace std;
struct Bomb {
int x;
int y;
Bomb *Next;
Bomb(){
Next = NULL;
x=0;
y=0;
}
int main()
{
srand(time(NULL));
Bomb *Starting = new Bomb; //setting up initial list...
Bomb *Ending = Starting;
int maxb,minb,numb;
cout << "Range Max: "; cin >> maxb; cout << endl;
cout << "Range Min: "; cin >> minb; cout << endl;
cout << "How Many? "; cin >> numb; cout << endl;
int i;for(i=0;i<numb;i++){
Ending->Next = new Bomb;
Ending->x = rand() % (maxb-minb+1) + minb; //also changed my min max algorithm, thanks to another post on this forum
Ending->y = rand() % (maxb-minb+1) + minb;
Ending = Ending->Next;
}
i=1;
Bomb *Temp = Starting->Next;
cout << "Bomb" << i << "\n\tX Coordinate: " << Starting->x << "\n\tY Coordinate: " << Starting->y << endl << endl;
while(Temp->Next != NULL){
i++;
cout << "Bomb" << i << "\n\tX Coordinate: " << Temp->x << "\n\tY Coordinate: " << Temp->y << endl << endl;
Temp = Temp->Next;
}
//deletion/deallocation of memory It used to look like this....
while(Starting->Next != NULL){ //Temp = Starting;
Temp=Starting; //delete Starting;
Starting=Temp->Next; //while(Temp->Next != NULL){
delete Temp; //Ending=Temp;
} //Temp=Temp->Next;
delete Starting; //delete Ending;}
return 0; //delete Temp;
}
haha thanks Gaminic. I was thinking that as I was lazily typing it in main. I had a slight mix up in my deletion loop. Note the changes. Let me know anyone if they notice any memory leaks.