Friday 17 February 2017

Implementation of Queue of string

#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<malloc.h>
using namespace std;  
struct Queue
{
    int front, rear, size;
    int  capacity;
    string * array;
};

// function to create a queue of given capacity. It initializes size of
// queue as 0
struct Queue* createQueue(int capacity)
{
    struct Queue* queue = (struct Queue*) malloc(sizeof(struct Queue));
    queue->capacity = capacity;
    queue->front = queue->size = 0;
    queue->rear = capacity - 1;  // This is important, see the enqueue
    queue->array = (string *) malloc(queue->capacity * sizeof(string));
    return queue;
}

// Queue is full when size becomes equal to the capacity
int isFull(struct Queue* queue)
{  return (queue->size == queue->capacity);  }

// Queue is empty when size is 0
int isEmpty(struct Queue* queue)
{  return (queue->size == 0); }

// Function to add an item to the queue.  It changes rear and size
void enqueue(struct Queue* queue, string item)
{
    if (isFull(queue))
        return;
    queue->rear = (queue->rear + 1)%queue->capacity;
    queue->array[queue->rear] = item;
    queue->size = queue->size + 1;
    cout<<"enqueued to queue  "<<item<<endl;
}

// Function to remove an item from queue.  It changes front and size
string dequeue(struct Queue* queue)
{
    if (isEmpty(queue))
         {cout<<"no";}
    string item = queue->array[queue->front];
    queue->front = (queue->front + 1)%queue->capacity;
    queue->size = queue->size - 1;
    return item;
}

// Function to get front of queue
string front(struct Queue* queue)
{
    if (isEmpty(queue))
       {cout<<"no";}
    return queue->array[queue->front];
}

// Function to get rear of queue
string rear(struct Queue* queue)
{
    if (isEmpty(queue))
         {cout<<"no";}
    return queue->array[queue->rear];
}


int main()
{
    struct Queue* queue = createQueue(1000);

    enqueue(queue, "abc");
    enqueue(queue, "egf");
    enqueue(queue, "hsaj");
    enqueue(queue, "hua");

    cout<<" dequeued from queue "<<dequeue(queue)<<endl;

   cout<<"Front item is "<<front(queue)<<endl;
    cout<<"Rear item is "<<rear(queue)<<endl;

    return 0;
}