Find Length of a Linked List (Iterative and Recursive) in C++

C++Server Side ProgrammingProgramming

Here we will see how to find the length of a linked list using iterative and recursive approaches. If the head pointer is given, we have to follow these steps to get the length.

  • For iterative approach −

    • Take the head of the list, until the current pointer is not null, go to the next node and increase the count.

  • For recursive approach −

    • Pass head as an argument, the base condition is when the argument is null, then return 0, otherwise recursively enter into the list and send the next node from the current node, return 1 + length of the sublist

Example

 Live Demo

#include<iostream>
using namespace std;
class Node {
   public:
      int data;
   Node* next;
};
void append(struct Node** start, int data) {
   struct Node* new_node = new Node;
   new_node->data = data;
   new_node->next = (*start);
   (*start) = new_node;
}
int count_recursive(Node* start) {
   if (start == NULL)
      return 0;
   return 1 + count_recursive(start->next);
}
int count_iterative(Node* start) {
   int count = 0;
   Node* current = start;
   while (current != NULL) {
      count++;
      current = current->next;
   }
   return count;
}
int main() {
   Node* start = NULL;
   append(&start, 1);
   append(&start, 3);
   append(&start, 1);
   append(&start, 2);
   append(&start, 1);
   cout << "Node count using iterative approach: " << count_iterative(start) << endl;
   cout << "Node count using recursion: " << count_recursive(start);
}

Output

Node count using iterative approach: 5
Node count using recursion: 5
raja
Published on 19-Dec-2019 14:29:56
Advertisements