यहां हम देखेंगे कि इटरेटिव और रिकर्सिव दृष्टिकोण का उपयोग करके लिंक्ड लिस्ट की लंबाई कैसे ढूंढें। यदि हेड पॉइंटर दिया गया है, तो लंबाई प्राप्त करने के लिए हमें इन चरणों का पालन करना होगा।
- इटरेटिव दृष्टिकोण के लिए -
- लिस्ट का हेड लें, जब तक वर्तमान पॉइंटर नल नहीं है, अगले नोड पर जाएं और काउंट बढ़ाएं।
- रिकर्सिव दृष्टिकोण के लिए -
- हेड को आर्गुमेंट के रूप में पास करें, बेस कंडीशन तब है जब आर्गुमेंट नल है, तो 0 वापस करें, अन्यथा रिकर्सिवली लिस्ट में प्रवेश करें और वर्तमान नोड से अगला नोड भेजें, 1 + सबलिस्ट की लंबाई वापस करें
उदाहरण
#includeusing 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); }
आउटपुट
Node count using iterative approach: 5 Node count using recursion: 5