Wednesday, July 25, 2012

Group a linked-list based on Vowels and Consonants.

You got to move the nodes having vowels as keys to the beginning and consonants to the end. You also got to maintain the order. Example:
Input: A-M-A-Z-O-N
Output: A-A-O-M-Z-N

Code (Complexity: O(N), Space O(1))

#include<iostream>
using namespace std;
 
class Node
{
public:
        char var;
        Node *next;
        
        Node(char v,Node *next=NULL):var(v),next(next){}
};
 
Node *make_list(char array[],int size)
{
        if(size ==0)
                return NULL;
        else
        {
                Node *head = new Node('o');
                Node *temp = head;
                for(int i=0;i<size;++i)
                {
                        temp->next = new Node(array[i]);
                        temp=temp->next;
                }
                temp=head;
                head = head->next;
                delete temp;
                return head;
        }
}
void print_list(Node *head)
{
        while(head){
                cout<<head->var<<"--";
                head = head->next;
        }
        cout<<"END"<<endl;
}
void insertAfter(Node** temp,Node *n)
{
        n->next = (*temp)->next;
        (*temp)->next = n;
}
bool isVowel(char v)
{
        switch(v)
        {
                case 'A':
                case 'E':
                case 'I':
                case 'O':
                case 'U':
                        return true;
                default:
                        return false;
        }
}
Node *groupByVowels(Node *head)
{
        Node *vowel=NULL,*consonant=NULL;
        
        vowel = new Node('L');
        consonant = new Node('C');
        
        Node *tv = vowel,*tc=consonant;
        for(Node *temp=head;temp;)
        {
                Node *tt = temp->next;
                if(isVowel(temp->var)){
                        insertAfter(&tv,temp);
                        tv = tv->next;
                }
                else{
                        insertAfter(&tc,temp);
                        tc=tc->next;
                }
                temp = tt;
        }
        tv->next = consonant->next;
        tv = vowel;
        vowel=vowel->next;
        delete tv;
        return vowel;
}
int main()
{
        char array[] = {'B','E'};
        Node *head = make_list(array,sizeof(array)/sizeof(array[0]));
        print_list(head);
        head = groupByVowels(head);
        print_list(head);
}

No comments:

Post a Comment