লিঙ্কড লিস্টের দৈর্ঘ্য দুটি পদ্ধতিতে বের করা: ইটারেটিভ (লুপ) এবং রিকারসিভ।
- ইটারেটিভ: হেড থেকে ট্রাভার্স করে কাউন্ট বাড়ান।
- রিকারসিভ: বেস কেস নাল হলে ০, অন্যথায় ১ + রিকারসিভ কল।
উদাহরণ
#include <iostream>
using namespace std;
struct Node { int data; Node* next; };
void append(Node** start, int data) {
Node* n = new Node; n->data = data; n->next = *start; *start = n;
}
int count_iterative(Node* start) {
int c = 0;
while (start) { c++; start = start->next; }
return c;
}
int count_recursive(Node* start) {
if (!start) return 0;
return 1 + count_recursive(start->next);
}
int main() {
Node* head = NULL;
append(&head, 1); append(&head, 3); append(&head, 1);
append(&head, 2); append(&head, 1);
cout << "Iterative: " << count_iterative(head) << endl;
cout << "Recursive: " << count_recursive(head);
return 0;
}
আউটপুট
Iterative: 5 Recursive: 5