统计链表中元音和辅音的数量
在这个问题中,我们需要统计给定链表中元音和辅音的总数。我们可以遍历链表并检查每个字符,判断它是辅音还是元音。
问题陈述 - 我们给定一个包含小写字母字符的链表。我们需要统计链表中元音和辅音的总数。
示例
输入
'a' -> 'b' -> 'e', 'c' -> 'd' -> 'e' -> 'f'’ -> 'o' -> 'i' -> 'a' -> 'a'
输出
Vowel – 7, constant - 4
解释 - 它包含 'b'、'c'、'd' 和 'f' 辅音,其他都是元音。
输入
a’ -> ‘e’ -> ‘i’ -> ‘o’ -> ‘u’
输出
Vowel – 5, constant - 0
解释 - 它包含输入字符串中的所有元音。
输入
'c' -> 'g' -> 'h' -> 'f'’ -> 'p' -> 'q' -> 'w' -> 'x'
输出
Vowel – 0, constant - 7
解释 - 输入字符串仅包含辅音。
方法 1
在这种方法中,我们将字符放入数组中。之后,我们将数组转换为链表。接下来,我们遍历链表并检查每个字符,判断它是元音还是辅音。
算法
步骤 1 - 定义 'listNode' 的 'struct' 类型以创建链表节点。
步骤 2 - 定义 addNode() 函数以在链表中插入节点。
步骤 2.1 - 在 addNode() 函数中创建一个新节点。同时,用给定的字符初始化其 'ch' 值,并将下一个节点初始化为 null 值。
步骤 2.2 - 如果起始节点为空,则将 temp 节点分配给起始节点。如果起始节点不为空,则遍历链表,找到最后一个节点,并在最后附加 temp 节点。
步骤 3 - 定义 isConst() 变量以检查特定字符是辅音还是元音。
步骤 4 - 定义 countVowelsAndConst() 函数以统计给定字符串中元音和辅音的总数。
步骤 5 - 将 'cons' 和 'vow' 变量初始化为零,分别存储辅音和元音的计数。
步骤 6 - 如果起始节点为空,则打印一条消息,说明列表不包含任何元音或辅音。
步骤 7 - 遍历链表,直到到达最后一个节点。获取当前节点的字符,并通过将字符作为参数传递来执行 isConst() 函数。
步骤 8 - 如果 isConst() 函数返回 true,则将 'cons' 变量的值增加 1。否则,将 'vow' 的值增加 1。
步骤 9 - 在循环中移动到下一个节点。
步骤 10 - 最后,打印 'vow' 和 'cons' 变量的值。
示例
#include <bits/stdc++.h>
using namespace std;
// creating the struct listNode
struct listNode {
int ch;
listNode *next;
} listNode;
// adding nodes to the linked list
void addNode(struct listNode **start, int ch) {
// creating a new node
struct listNode *temp = new struct listNode();
// add ch to the node
temp->ch = ch;
temp->next = NULL;
// if the list is empty, add a node to the list
if (*start == NULL) {
*start = temp;
} else {
// If the list has some nodes, append the node at the end of the list
struct listNode *pointer1 = *start;
while (pointer1->next != NULL) {
pointer1 = pointer1->next;
}
pointer1->next = temp;
}
}
bool isConst(char ch) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
return false;
}
return true;
}
// Counting vowels and consonants
void countVowelsAndConst(struct listNode *start) {
int vow = 0;
int cons = 0;
// if the list is empty
if (start == NULL) {
cout << "List is not containing any vowels and constants" << endl;
return;
}
// traverse the linked list
while (start != NULL) {
if (isConst(start->ch)) {
cons++;
} else {
vow++;
}
start = start->next;
}
cout << "Total counts of the vowel in the list is " << vow << endl;
cout << "Total counts of the consonant in the list is " << cons << endl;
}
int main() {
int arr[] = {'a', 'b', 'e', 'c', 'd', 'e', 'f', 'o', 'i', 'a', 'a'};
int len, p;
// create an empty linked list
struct listNode *start = NULL;
len = sizeof(arr) / sizeof(arr[0]);
// inserting characters of the array to a linked list
for (p = 0; p < len; p++)
addNode(&start, arr[p]);
countVowelsAndConst(start);
return 0;
}
输出
Total counts of the vowel in the list is 7 Total counts of the consonant in the list is 4
时间复杂度 - O(N),因为我们遍历了链表。
空间复杂度 - O(1),因为计数操作不占用任何空间。
我们统计了给定链表中元音和辅音的总数。程序员还可以统计给定链表中特定字符的频率,以进行更多练习。
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP