I disagree with that last statement, ninebit. Truth is, linked lists teach us a LOT about the theory of programming, and should be studied earnestly by all coders.
Code:
void Escape( char *msg );
struct node{
int age;
char name[MAX];
node *next;
};
int main()
{
bool initialized = false;
int amount;
node *head;
node *newNode;
node *go;
node *goner;
head = (node*)malloc(sizeof(node));
if(head == NULL)
{
Abort("This Program Has Performed An Illegal Operation And Will Be Shut Down!!");
}
strncpy(head->name, "I never use the head for data...", MAX);
head->next = NULL; //...THIS IS REQUIRED!!!
cout<<"How many people to be stored";
cin >> amount;
for( int start=0; start < amount; start++)
{
newNode = (node*)malloc(sizeof(node));
if(newNode == NULL) //...panic!
break;
if( !initialized )
{
head->next = newNode;
initialized = true;
}
newNode->next = NULL; //...Note: forget this == sudden death!
sprintf(ptr->name," %i) ANTHONY", start);
cout << ptr->name;
}
go = head;
while(go->next)
{
goner = go;
go = go->next; //..advance to next structure...
if( goner != NULL )
{
free(goner);
}
}
if( go != NULL ) free(go); //...free the very last cell...
getch();
return 0;
}
void Escape( char *msg )
{
clrscr();
puts("\n\n\n\n\n\n\n\n\n");
printf(" %s", msg );
puts("\n\n\n\n\n\n ");
getch();
exit(-1);
}
The most important point about linked lists is:
-ALWAYS initialize "next" to 0 or NULL.
-ALWAYS check new pointers for NULLness
-ALWAYS check pointers for NULLness before deleting
-Always perfect a method and encapsulate in a function!!