编写一个 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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP