এই সমস্যায়, আমাদের একটি লিঙ্কড লিস্ট দেওয়া আছে। আমাদের কাজ হল একটি ফাংশন তৈরি করা যা লিঙ্কড লিস্টে একটি দেওয়া সংখ্যা কতবার ঘটেছে তা গণনা করতে পারবে।
একটি উদাহরণ নিয়ে সমস্যাটি বুঝি,
ইনপুট
লিঙ্কড লিস্ট = 10-> 50 -> 10 -> 20 -> 100 -> 10, int = 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<<"লিঙ্কড লিস্টে ১০-এর গণনা "<<countInt(head, 10); return 0; }
আউটপুট
লিঙ্কড লিস্টে ১০-এর গণনা 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<<"লিঙ্কড লিস্টে ১০-এর গণনা "<<countInt(head, 10); return 0; }
আউটপুট
লিঙ্কড লিস্টে ১০-এর গণনা 3