इस समस्या में, हमें एक लिंक्ड लिस्ट दी गई है। हमारा कार्य एक ऐसा फ़ंक्शन बनाना है जो लिंक्ड लिस्ट में दी गई संख्या की घटनाओं की संख्या गिन सके।
उदाहरण
इनपुट
लिंक्ड लिस्ट = 10 -> 50 -> 10 -> 20 -> 100 -> 10, int = 10
आउटपुट
3
व्याख्या - संख्या 10 लिंक्ड लिस्ट में 3 बार होती है।
इस समस्या का समाधान सरल है, बस लिंक्ड लिस्ट को ट्रैवर्स करें और एक काउंटर बढ़ाएं जब वर्तमान नोड का मान दी गई संख्या के बराबर हो।
लिंक्ड लिस्ट के नोड्स पर लूपिंग को इटरेशन के साथ-साथ रिकर्सन का उपयोग करके भी किया जा सकता है और हम समस्या को हल करने के लिए दोनों विधियों को चित्रित कर रहे हैं।
इटरेशन का उपयोग करके समाधान दिखाने वाला प्रोग्राम,
उदाहरण
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
};
void push(Node** head_ref, int new_data) {
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int countInt(Node* head, int search_for) {
Node* current = head;
int intCount = 0;
while (current != NULL) {
if (current->data == search_for)
intCount++;
current = current->next;
}
return intCount;
}
int main() {
Node* head = NULL;
push(&head, 10);
push(&head, 40);
push(&head, 10);
push(&head, 50);
push(&head, 20);
push(&head, 90);
push(&head, 10);
cout << "लिंक्ड लिस्ट में 10 की गिनती: " << countInt(head, 10);
return 0;
}
आउटपुट
लिंक्ड लिस्ट में 10 की गिनती: 3
रिकर्सन का उपयोग करके समाधान दिखाने वाला प्रोग्राम,
उदाहरण
#include <iostream>
using namespace std;
int intCount = 0;
class Node {
public:
int data;
Node* next;
};
void push(Node** head_ref, int new_data) {
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int countInt(struct Node* head, int key) {
if (head == NULL)
return intCount;
if (head->data == key)
intCount++;
return countInt(head->next, key);
}
int main() {
Node* head = NULL;
push(&head, 10);
push(&head, 40);
push(&head, 10);
push(&head, 50);
push(&head, 20);
push(&head, 90);
push(&head, 10);
cout << "लिंक्ड लिस्ट में 10 की गिनती: " << countInt(head, 10);
return 0;
}
आउटपुट
लिंक्ड लिस्ट में 10 की गिनती: 3