在这个问题上,我们得到了一个链表。我们的任务是创建一个函数,该函数将能够计算给定数字在链接列表中出现的次数。
让我们举个例子来了解这个问题,
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