-
linked list example
It's a while since I did linked lists is the following prog fine and if not why not.
Code:
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
#define MAX 30
struct node{
int age;
char name[MAX];
node *next; /* pointer to next node */
};
int main()
{
int amount;
node *top; /* pointers to a structure of type node */
node *newnode;
node *start;
node *hold;
top=(node*)malloc(sizeof(node)); /* set memory aside for first node */
if(top==NULL)
abort(); /* abnormal program termination */
cout<<"How many people to be stored >";
cin>>amount;
if(amount==0)
{
free(top); /* only memory set aside for top node freed */
exit(0); /* terminate program */
}
cout<<"Input your name >"; /* we can only write to the top node(structure) at the moment */
cin>>top->name;
cout<<'\n'<<"Input your age";
cin>>top->age;
for(int start=1;start<amount;start++) /* start initialised to one as the first node has been filled */
{
newnode=(node*)malloc(sizeof(node)); /* set memory aside for the new node */
top->next=newnode; /* pointer to top node points to next which is a pointer to a newnode */
/* which is assigned to next */
cout<<'\n'<<"Input your name >"; /* write to next nodes */
cin>>newnode->name;
cout<<'\n'<<"Input your age";
cin>>newnode->age;
newnode->next=NULL; /* last node must point to NULL */
}
cout<<top->name<<' '<<top->age;
cout<<'\n'<<newnode->name<<' '<<newnode->age;
start=top; /* node pointer start points to top/first node in the list */
for(int begin=0;begin<amount;begin++)
{
hold=start; /* assign each node to a holding node so we can free */
/* its memory later */
start=start->next; /* start is now pointing to the next node */
if(hold!=NULL)
cout<<'\n'<<"Memory freed",free(hold);
}
getch();
return 0;
}
Thanks for all the help.
Please use [code][/code]Tags
-
Here is a good article on linked lists, with an example in C++.