Find the Length of a Linked List
Written by
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:
- Create a linked list
- Create some nodes of this list.
- Iterate till we reach an element whose node points to NULL
- 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->data = 2; second->data = 16; third->data = 13; fourth->data = 1; fifth->data = 34; head->next = second; second->next = third; third->next = fourth; fourth->next = fifth; fifth->next = NULL; searchList(head); return 0;
}
Output:
Length of list is 5
This is how we find the length of a linked list.