Given a Singly Linked List. The task is to check if the characters in a node is vowel if yes then toggle the case of the vowel.
Examples:
Input : C-> p-> l-> u-> s-> p-> l-> u-> s
Output : C p l U s p l U s
The nodes with vowels are ‘u’ toggle the case of the Vowels hence the nodes are ‘U’.Input : J->U->N->K->V->I->R->U->S->NULL
Output : J u N K V i R u S
Simple Approach:
- Traverse through all the nodes in the list
- Check if the data in the node is a vowel
- If the character is a vowel then toggle the case of the vowel
Implementation of the simple approach:
#include <bits/stdc++.h>
using namespace std;
// A Linked List Node
struct Node {
char data;
struct Node* next;
};
// Utility function to create a new node
Node* newNode(char data)
{
Node* temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
// Utility function to print the list
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}
// Function to check if a character is a vowel
bool isVowel(char c)
{
c = tolower(c);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
return true;
return false;
}
// function to toggle the case of the vowels in the list
void toggleCase(Node* head)
{
Node* p = head;
// Traverse through the nodes in the list
while (p != NULL) {
char c = p->data;
// If the character is a vowel
if (isVowel(c)) {
// toggle the case of the vowel
if (isupper(c))
c = tolower(c);
else
c = toupper(c);
}
p->data = c;
p = p->next;
}
}
// Driver function
int main()
{
Node* head = newNode('C');
head->next = newNode('p');
head->next->next = newNode('l');
head->next->next->next = newNode('u');
head->next->next->next->next = newNode('s');
head->next->next->next->next->next = newNode('p');
head->next->next->next->next->next->next = newNode('l');
head->next->next->next->next->next->next->next = newNode('u');
head->next->next->next->next->next->next->next->next = newNode('s');
toggleCase(head);
printList(head);
return 0;
}
Output:
C p l U s p l U s
Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.
