TutorialStudyMite
Find the Length of a Linked List
AAnshuman Raina1 min read
Beginner friendly
Track completion, mastery, and revision.
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;
}Output:
Length of list is 5This is how we find the length of a linked list.
Finished reading?