Find Length of a Linked List
We can find the length of a linked list by initializing a counter to zero and incrementing it for every node of linked list. We will traverse the linked list from start and go until we reach the end of it.
In the above linked list, we can see there are 4 nodes and hence, the legth of this linked list would be 4.
Let's implement the appraoch to calculate the length of a linked list.
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data; // holds the data
node* next; // hold the pointer to next node
};
node* add_new_node(node* head, int data)
{
// adds new node into the LL in the end
// takes the pointer to head of LL as arg
// and the data which is to be added
// create a new node to add in LL
node* new_node = new node();
// pass the data of arg to new node
new_node->data = data;
// set the next to null as its last node.
new_node->next = NULL;
// set it to point to head of LL
node *temp = head;
// reach the last node
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next = new_node;
return head;
}
int countNodes(node* head)
{
int counter = 0;
while(head != NULL)
{
counter ++;
head = head->next;
}
return counter;
}
int main()
{
node* head = new node();
head->data = 1;
head->next = NULL;
head = add_new_node(head, 2);
head = add_new_node(head, 3);
head = add_new_node(head, 4);
cout<<"Total nodes in LL are "<<countNodes(head)<<endl;
return 0;
}
Total nodes in LL are 4