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:

  1. Create a linked list
  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 *head = NULL; Node *second = NULL; Node *third = NULL; Node *fourth = NULL; Node *fifth = NULL;

head = new Node();
second = new Node();
third = new Node();
fourth = new Node();
fifth = new Node();

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

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

searchList(head);
return 0;

}

Output:

Length of list is 5

This is how we find the length of a linked list.

Find the Length of a Linked List