Program to find size of Doubly Linked List in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find size of Doubly linked list.

For this we will be provided with a doubly linked list. Our task is to find the size of that linked list i.e the number of elements in the linked list.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//structure of linked list node
struct Node {
   int data;
   struct Node *next;
   struct Node *prev;
};
void push(struct Node** head_ref, int new_data) {
   struct Node* new_node = new Node;
   new_node->data = new_data;
   new_node->next = (*head_ref);
   new_node->prev = NULL;
   if ((*head_ref) != NULL)
      (*head_ref)->prev = new_node ;
   (*head_ref) = new_node;
}
//returning size of linked list
int findSize(struct Node *node) {
   int res = 0;
   while (node != NULL){
      res++;
      node = node->next;
   }
   return res;
}
int main() {
   struct Node* head = NULL;
   push(&head, 4);
   push(&head, 3);
   push(&head, 2);
   push(&head, 1);
   cout << findSize(head);
   return 0;
}

Output

4
raja
Published on 19-May-2020 15:24:54
Advertisements