# Find the Length of a Linked List

Written by

Anshuman Raina

### Find the Length of a Linked List

THEORY:

Calculating the Length of a linked list is pretty easy, given we have already seen how to get an element in a linked list (see Search for element).

Input : [1,3,4,5]

Output: 4

### # Algorithm

We intend to do as follows:

2. Create some nodes of this list.
3. Iterate till we reach an element whose node points to NULL
4. Initialize count as 0, and increment at each iteration

Code:

``````#include <iostream>
using namespace std;
struct Node{
int data;
Node * next;
};
void searchList(Node *n){
int count = 0;
do {
count++;
n = n->next;
} while (n != NULL);
cout << "Length of list is " << count << endl;
}
int main(){
Node *second = NULL;
Node *third = NULL;
Node *fourth = NULL;
Node *fifth = NULL;
second = new Node();
third = new Node();
fourth = new Node();
fifth = new Node();

second-&gt;data = 16;
third-&gt;data = 13;
fourth-&gt;data = 1;
fifth-&gt;data = 34;

second-&gt;next = third;
third-&gt;next = fourth;
fourth-&gt;next = fifth;
fifth-&gt;next = NULL;

````}````
``Length of list is 5``