The following is the code I have written to solve the particular problem. But I am having problems with solving two edge cases. The case where the first element itself is a vowel, and the case where the last element is the vowel. Now as for the first edge case, I think it can be solved by iterating through the list till we find a vowel, and inserting the head node before the said node, and update the head pointer. But in the 2nd case, the case where the last element is a vowel, in that case, my code is running into an infinite loop. How can I handle that particular case? Also, if you can suggest any different approach towards solving the problem, please do so and if you can, please suggest any kind of improvement I can apply in the code.
#include<iostream>
using namespace std;
struct node
{
char ch;
node *next;
};
void enqueue (node **head, node **tail, char val)
{
node *newn = (node *)malloc(sizeof(node));
newn->ch = val;
newn->next = NULL;
if (*head == NULL)
{
*head = newn;
*tail = newn;
}
(*tail)->next = newn;
(*tail) = newn;
}
void print (node *head)
{
while (head!=NULL)
{
cout<<head->ch<<" ";
head = head->next;
}
cout<<endl;
}
bool isVowel (char ch)
{
ch = ch | 32;
if (ch == 'a' || ch =='e' || ch=='i' || ch=='o' || ch=='u')
return true;
return false;
}
node* segregateVowels (node *head, node *tail)
{
if (head == NULL)
return head;
node *temp = head;
node *fin = tail;
while (temp!=fin)
{
cout<<temp->ch<<" "<<fin->ch<<endl;
getchar();
if (isVowel(temp->next->ch))
{
node *shift = temp->next;
temp->next = temp->next->next;
tail->next = shift;
shift->next = NULL;
tail = shift;
}
else
temp = temp->next;
}
return head;
}
int main()
{
srand(time(NULL));
node *head = NULL, *tail = NULL;
int i = 20;
while (i>=0)
{
enqueue (&head, &tail, rand()%26+65);
i--;
}
print(head);
head = segregateVowels (head, tail);
print(head);
}