以下は、特定の問題を解決するために私が書いたコードです。しかし、2 つのエッジ ケースの解決に問題があります。最初の要素自体が母音の場合と、最後の要素が母音の場合です。最初のエッジ ケースについては、母音が見つかるまでリストを反復処理し、そのノードの前にヘッド ノードを挿入し、ヘッド ポインタを更新することで解決できると思います。しかし、最後の要素が母音である 2 番目のケースでは、その場合、私のコードは無限ループに陥っています。その特定のケースをどのように処理できますか?また、問題を解決するための別のアプローチを提案できる場合は、そうしてください。可能であれば、コードに適用できるあらゆる種類の改善を提案してください。
#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);
}