+92 332 4229 857 99ProjectIdeas@Gmail.com

How to count total number of nodes in singly linked list (C++)


Counting nodes in the linked list
GetCount() returns the total number of nodes in the linked list. It takes the head pointer of the linked list as its input parameter.
Summary of GetCount()
The logic for counting the total number of nodes in the linked list is similar for displaying the data, in this case only a counter is used. As the loop iterates till the end of linked list, count variable is increamented each time. And at the end of the while loop the count variable is returned from the function.
int count=0;
              while(temp!=NULL)
              {
                     count=count+1;
                     temp=temp->link;
              }
return count;

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);
       int GetCount(Node*);
};

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;
       }
}

int LinkList::GetCount(Node*temp)
{
       int count=0;
              while(temp!=NULL)
              {
                     count=count+1;
                     temp=temp->link;
              }
return count;
}

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);

       // Counting total nodes in the linked list
       cout<<"Total number of nodes in the linked list are : ";
       cout<<l.GetCount(l.head);
       cout<<endl;

       _getche();
       return 0;
}

Output
Total number of nodes in the linked list are : 5

0 comments: