No offence, but that there's some UGLY code! Anyway, here's what I'd do:
(1) Never use the head for data!! Always leave it data-empty.
(2) If this is a C++ class, then the initializing of new objects should be done in the constructor.
(3) If this is NOT a C++ class, then write a function called Init( List *New){} or similar and use it! This will save you from simple errors.
Here is a way to do what you want:
Code:
Class Node { public:
Node *next;
int data;
Node(){ next = 0, data = 0;} //...constructor...
//...Load will append to end of list.
bool Load( char *filename )
{
//...open file for reading...
Node *t = this;
while(t->next !=NULL)
{
t = t->next;
}
while(!level.eof())
{
Node *born = new Node;
if(born == NULL)
//...couldn't allocate, close file and return false...
//...read in data...
t->next = born;
t = t->next;
}
//...close file and return true...
}
void Kill()
{
Node *t = this;
if( t->next == NULL)
return;
t = t->next;
while(t->next != NULL)
{
loser = t;
t = t->next;
delete loser;
}
delete t;
}
};
int main()
{
Node head;
head.Load("myfile.dat");
head.Kill();
head.Load("another.dat");
head.Kill();
return 0;
}