Trong bài toán này, chúng ta được cho một danh sách liên kết. Nhiệm vụ là tạo một hàm có thể đếm số lần một số cho trước xuất hiện trong danh sách liên kết.
Hãy xem ví dụ để hiểu bài toán,
Đầu vào
Danh sách liên kết = 10-> 50 -> 10 -> 20 -> 100 -> 10, int = 10
Đầu ra
3
Giải thích - số 10 xuất hiện 3 lần trong danh sách liên kết.
Giải pháp cho bài toán này đơn giản, chỉ cần duyệt danh sách liên kết và tăng bộ đếm khi giá trị nút hiện tại bằng số cho trước.
Việc lặp qua các nút của danh sách liên kết có thể làm bằng lặp cũng như đệ quy và chúng ta minh họa cả hai phương pháp giải bài toán.
Chương trình minh họa giải pháp dùng lặp,
Ví dụ
#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<<"Số lần xuất hiện của 10 trong danh sách liên kết là "<<countInt(head, 10); return 0; }Đầu ra
Số lần xuất hiện của 10 trong danh sách liên kết là 3
Chương trình minh họa giải pháp dùng đệ quy,
Ví dụ
#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<<"Số lần xuất hiện của 10 trong danh sách liên kết là "<<countInt(head, 10); return 0; }Đầu ra
Số lần xuất hiện của 10 trong danh sách liên kết là 3