• • In this blog post we will learn how to count the number of nodes in a linked list using c/ c++ program. to count linked list nodes we have to traverse the linked list from head to tail. It is generally asked in programming job interview.

### write a c program to count the number of linked list nodes.

For example in the below figure ,there are 5 nodes in the linked list. ### Sample code for how to count the number of nodes in a linked list

C/C++ program:- ( iterative method)

```#include<stdio.h>
#include<stdlib.h>

// data structure for link list
typedef struct list {
int data; //data
struct list *next; // point to next node
} list;

void insert(int a);

int count = 0;
if (p == NULL) {
return 0;
}
while (p != NULL) {
count++;
p = p->next;
}
return count;
}

int main() {
// insert 1 to 5 in linked list
int i = 0;
for (i = 1; i < 6; i++) {
insert(i);
}
// count
printf("there are %d nodes in linked list\n",num_of_nodes);
return 0;
}

void insert(int a) {
// create first node
} else {
// go to last node

while (p->next != NULL)
p = p->next;
// create new node
list *new_one = (list *) malloc(sizeof(list));
new_one->data = a;
p->next = new_one;
new_one->next = NULL;
}
}
```

C/C++ program:- ( recursive method):-

```#include<stdio.h>
#include<stdlib.h>

// data structure for link list
typedef struct list {
int data; //data
struct list *next; // point to next node
} list;

void insert(int a);

int count = 0;
if (p == NULL) {
return 0;
}
while (p != NULL) {
count++;
p = p->next;
}
return count;
}
int count_r(list * head, int count) {
}

int main() {
// insert 1 to 5 in linked list
int i = 0;
for (i = 1; i < 6; i++) {
insert(i);
}
// count
printf("there are %d nodes in linked list\n",num_of_nodes);
return 0;
}

void insert(int a) {
// create first node
} else {
// go to last node

while (p->next != NULL)
p = p->next;
// create new node
list *new_one = (list *) malloc(sizeof(list));
new_one->data = a;
p->next = new_one;
new_one->next = NULL;
}
}
```

## How recursive method works here?

```int count_r(list * head, int count) {