Basic Structure
Let’s define the basic structure of our node. I will be using a class here; you can even use structures for this purpose.
class stud
{
char name[20];
int berth;
public:
void add(); //to add a node
void insert(); //to insert a node
void del(); //to delete a node
void display();//to display all the linked nodes
stud *next; //next part of your node
};*x,*l,*f,s; //objects of the class
Creating node(s)
Now let’s make the add function.
void stud::add()
{
int n;
cout<<"Enter the number of elements you would like to create";
cin>>n;
f=new stud; //Assigning the pointer some memeory.
cin>>f->name;
cin>>f->berth;
f->next=NULL; //safer side without any dangling pointer.
l=f;
for(int i=0;i<(n-1);i++) // n-1 as we have already created a node above.
{
x=new stud;
cin>>x->name>>x->berth;
x->next=NULL;
l->next=x;
l=x;
}
}
Displaying the linked list
void stud :: display()
{
l=f; // starting from the first node.
while(l!=NULL) //traversing the l pointer till the end
{
cout<<l->name<<l->berth; // dispaying name and berth no. of node
l=l->next; // shifting l to the next node.
}
}
I have included comments in the program itself so that you can understand there and then.
Insert and Delete functions coming in a while. Till the time being, give the above functions a try and let me know if you have any problem with it.
Pages: 1 2
