编写一个函数来计算给定int在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
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下