Saturday, 14 November 2015

Object Oriented Implementation of Queue using arrays is C

Hi Friends..Following is a simple code for Queue using arrays. The difference is that it is implemented in C++ style. I have checked it on my system and is working perfectly. You can use this code freely for educational purpose. Please leave comments and let me know if you see any scope for improvement. I will modify this here and increment revision number
/*Rev 0: First implementation*/

#include <stdlib.h>
#include <stdio.h>

#define MAX_SIZE 10

typedef struct QueueClass
{
    char q[MAX_SIZE];
    unsigned int DataCount;
    unsigned int Head;
    unsigned int Tail;
    char (*Enque)(void*,char);
    char (*Deque)(void*);
    unsigned int (*Size)(void*);
    char (*GetData)(void*);
}  CLASS_QUEUE;



char Enque(void* object, char data)
{
    CLASS_QUEUE *LocalObject = (CLASS_QUEUE*) object;
    if(LocalObject->DataCount >= MAX_SIZE)
    {
        printf("Overflow\n");
        return -1;
    }
    LocalObject->Head = (LocalObject->Head + 1)% MAX_SIZE;
    LocalObject->q[LocalObject->Head] = data;
    LocalObject->DataCount++;
    return data;
    }
   
char Deque(void* object)
{
    CLASS_QUEUE *LocalObject = (CLASS_QUEUE*) object;
    if(LocalObject->DataCount <= 0)
    {
        printf("Underflow\n");
        return -1;
    }
    LocalObject->Tail = (LocalObject->Tail + 1) % MAX_SIZE;
    LocalObject->DataCount--;
    return LocalObject->q[LocalObject->Tail];
}
   
unsigned int Size(void* object)
{
    CLASS_QUEUE *LocalObject = (CLASS_QUEUE*) object;
    return LocalObject->DataCount;
}

char GetData(void* object)
{
    CLASS_QUEUE *LocalObject = (CLASS_QUEUE*) object;
    return LocalObject->q[LocalObject->Head];
}  
   
CLASS_QUEUE * QueueConstructor()
{
    CLASS_QUEUE * Object = (CLASS_QUEUE*)malloc(sizeof(CLASS_QUEUE));
    Object->DataCount = 0;
    Object->Head = -1;
    Object->Tail = -1;
    Object->Enque = Enque;
    Object->Deque = Deque;
    Object->Size = Size;
    Object->GetData = GetData;
    return Object; 
}
   
   
int main()
{
    int x=0;
    unsigned char Key;
    CLASS_QUEUE * q1= QueueConstructor();
    while(1)
    {
        printf("Hit e to enque, d to deque or q to quit");
        while((Key = getchar())=='\n');
       
        if(Key == 'e')
            printf("%d\n",q1->Enque(q1,x++));
        else if(Key == 'd')
            printf("%d\n",q1->Deque(q1));
        else if(Key == 'q')
            break;
    }
    printf("%d\n",q1->Size(q1));
    free(q1);
    return 0L;
}