ronith
10/31/2018 - 9:01 AM

Arrange consonants and vowels nodes in a linked list

//https://www.geeksforgeeks.org/arrange-consonants-vowels-nodes-linked-list/
#include <iostream>
using namespace std;

struct LL {
    char data;
    struct LL *next;
};
typedef struct LL node;

void push (node **headref, char c) {
    node *temp= (node*)malloc(sizeof(node));
    temp->data= c;
    temp->next= NULL;

    if (*headref== NULL) {
        *headref= temp;
        return;
    }
    node *last= *headref;
    while (last->next)
        last= last->next;
    last->next= temp;
}
void print (node *n) {
    while (n) {
        cout<< n->data<< " ";
        n= n->next;
    }
    return;
}
bool isVowel(char x)  {
    return (x == 'a' || x == 'e' || x == 'i' ||
            x == 'o' || x == 'u');
}
node* func(node *head) {
    node *newHead= head;

    node *lastVowel;
    node *curr= head;
    if (head== NULL)
        return NULL;
    if (isVowel(head->data))
        lastVowel= head;
    else {
        while (curr->next && !isVowel(curr->next->data))
            curr= curr->next;
        if (curr->next== NULL)
            return head;
        lastVowel= newHead= curr->next;
        curr->next= curr->next->next;
        lastVowel->next= head;
    }
    while (curr && curr->next) {
        if (isVowel(curr->next->data)) {
            if (curr== lastVowel)
                lastVowel= curr= curr->next;
            else {
                node *temp= lastVowel->next;
                lastVowel->next= curr->next;
                lastVowel= lastVowel->next;
                curr->next= curr->next->next;
                lastVowel->next= temp;
            }
        }
        else {
            curr= curr->next;
        }
    }
    return newHead;
}
int main() {
    node *head= NULL;
    push (&head, 'a');
    push (&head, 'e');
    push (&head, 'g');
    push (&head, 'h');
    push (&head, 'i');
    push (&head, 'm');
    push (&head, 'p');
    push (&head, 'e');
    push (&head, 'r');
    push (&head, 'm');
    push (&head, 'u');

    print(head);
    head= func(head);
    cout<<endl;
    print(head);
}