So in this article we will be studying about Linked List and its implementation and traversal in C and C++.
Firstly the very first question is, What is a Linked List?
The answer to this question is that a Linked List is a set of data elements of same type, each containing a link to its successor (and sometimes its predecessor). By saying 'same type' i don't mean that it should have the same data type, but if we consider the information of 1 student in some database as a structure then all the nodes of the linked list should be of the same student structure
So that's how a node is represented where the bigger rectangle is the information part and the small rectangle is the l,ink part. The Link part contains the address of the successor node(in case of a single headed linked list).
The link part of the last node contains NULL.
struct node
{ int adno;
char name[20];
float mks;
node *link;
};
So that's how a structure of node can be declared where node *link is called the self referential structure. Where self referential structure means any structure which has a pointer holding the address of a similar structure.
Syntax in C++ for traversal
void display(){
if(start==NULL)
{
cout<<"Link list empty "<<'\n';
getch();
exit(0);
}
node*ptr;
ptr=start;
while(ptr!=NULL)
{
cout<<"Admission no : "<<ptr->adno<<'\n';
cout<<"Name : "<<ptr->name<<'\n';
cout<<"Marks : "<<ptr->mks<<'\n';
cout<<"______________________________________"<<'\n';
ptr=ptr->link;
}
}
Syntax in C for traversal
void display()
{node *ptr=(NODE*)malloc(sizeof(NODE));
if(start==NULL)
{
printf("\nLink list empty ");
getch();
exit(0);
}
ptr=start;
while(ptr!=NULL)
{
printf("\nAdmission no : %d",ptr->adno);
printf("\nName : %s",ptr->name);
ptr=ptr->link;
}
}
ptr=ptr->link;
By this line we are basically going the the next node by assigning the addre3ss of the next node to the current pointer.
For more detailed explanation do go through our video on linked list and its traversal..
No comments:
Write comments