編寫一個 C++ 函式,統計給定整數在一個連結串列中出現的次數。
在這個問題中,我們給定一個連結串列。我們的任務是建立一個函式,能夠計算給定數字在連結串列中出現的次數。
讓我們舉個例子來理解這個問題:
輸入
Linked list = 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<<"The count of 10 in the linked list is "<<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<<"The count of 10 in the linked list is "<<countInt(head, 10); return 0; }
輸出
The count of 10 in the linked list is 3
廣告