Now, we will see how to find the number of nodes in single link list:
Algorithm to find number of nodes in the list:
- Set TEMP = START
- Set COUNT = 0
- While (TEMP != NULL)
- COUNT = COUNT + 1
- TEMP = TEMP->NEXT
- End While;
- Return COUNT
Function to count number of node in link list:
int countNodes(NODE **start){
NODE *temp = *start;
int count = 0;
while(temp != NULL){
count++;
temp = temp->next;
}
return count;
}
Program to count number of nodes in the link list:
#include <stdio.h>
#include <malloc.h>
struct node{
int info;
struct node *next;
};
typedef struct node NODE;
void insertAtFirst(NODE **, int);
int countNodes(NODE **);
int main(){
NODE *start = NULL;
insertAtFirst(&start, 4);
insertAtFirst(&start, 5);
insertAtFirst(&start, 6);
printf("\nThe list have %d nodes\n", countNodes(&start));
return 0;
}
int countNodes(NODE **start){
NODE *temp = *start;
int count = 0;
while(temp != NULL){
count++;
temp = temp->next;
}
return count;
}
void insertAtFirst(NODE **start, int info){
NODE *ptr = (NODE*) malloc(sizeof(NODE));
ptr->info = info;
ptr->next = *start;
*start = ptr;
}
The list have 3 nodes
Comments
Post a Comment