Displaying nodes in the linked list
DisplayWhole() function prints all the data contained in the nodes.
Summary of DisplayWhole()
The logic for displaying the data in the linked list is very simple, first of all a pointer is created to the node say temp:
Node*temp=head;
After the creation of temp,it is initialized with the head of the linked list, after assigning head to the temp, a do-while loop traverses all the linked list node by node and the data is displayed.
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp=temp->link;
}
Code
#include "stdafx.h"
#include "iostream"
#include "conio.h"
using namespace std;
struct Node
{
public:
int data;
Node*link;
Node();
};
Node::Node()
{
data=0;
link=NULL;
}
class LinkList
{
public:
Node*head;
LinkList();
void AddNodeAtEnd(int);
void DisplayWhole();
};
LinkList::LinkList()
{
head=NULL;
}
void LinkList::AddNodeAtEnd(int _data)
{
Node*node=new Node();
node->data=_data;
node->link=NULL;
if(head==NULL)
head=node;
else
{
Node*tptr=head;
while(tptr->link!=NULL)
tptr=tptr->link;
tptr->link=node;
}
}
void LinkList::DisplayWhole()
{
Node*temp=head;
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp=temp->link;
}
}
int main()
{
LinkList l;
// Adding first element to the linked list
l.AddNodeAtEnd(10);
// Adding second element to the linked list
l.AddNodeAtEnd(20);
// Adding third element to the linked list
l.AddNodeAtEnd(30);
// Adding fourth element to the linked list
l.AddNodeAtEnd(40);
// Adding fifth element to the linked list
l.AddNodeAtEnd(50);
// Displaying all nodes in the linked list
cout<<"Nodes in the linked list are : "<<endl;
l.DisplayWhole();
cout<<endl;
_getche();
return 0;
}
Output
Nodes in the linked list are :
10
20
30
40
50
0 comments:
Post a Comment