Learn the implementation of queue

Learn queue

Queue is a abstract datatype which servers  (FIFO) First In First Out manner .The basic operation of the queue is enqueue and dequeue .
enqueue is the insertion of the elements at the one end of the queue and
dequeue is the deletion of the element from queue form same end

How to understand queue :

lets take an example of real world at ATM .the person who came first is given accesses to ATM machine and after completion of his work the next person standing after him is given the next access

The operations of queue are :

  • Enqueue (insertion of element in the queue)
  • Dequeue (deletion of element from queue)

Enqueue and Dequeue operation :

in enqueue operation there are 2 data pointers front and rear
initially the R and F pointer is at -1 to say that queue is empty 
the inserting of the queue takes place from rear end and deletion from front end thus we take  as front and R as rear variables to implement queue lets add element by incrementing pointer and insert the element as well to delete the element increase F pointer

void enqueue(int queue[], int element, int& rear, int arraySize) {
    if(rear == arraySize)            // Queue is full
            printf(“OverFlow\n”);
    else{
         queue[rear] = element;    // Add the element to the back
         rear++;
    }
}

void dequeue(int queue[], int& front, int rear) {
    if(front == rear)            // Queue is empty
        printf(“UnderFlow\n”);
    else {
        queue[front] = 0;        // Delete the front element
        front++;
    }
}

Implementation of queue :

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

using namespace std;

void enqueue(char queue[], char element, int& rear, int arraySize) {
    if(rear == arraySize)            // Queue is full
        printf("OverFlow\n");
    else {
        queue[rear] = element;    // Add the element to the back
        rear++;
    }
}


void dequeue(char queue[], int& front, int rear) {
    if(front == rear)            // Queue is empty
        printf("UnderFlow\n");
    else {
        queue[front] = 0;        // Delete the front element
        front++;
    }
}

char Front(char queue[], int front) {
    return queue[front];
}


int main() {
    char queue[20] = {'a', 'b', 'c', 'd'};        
    int front = 0, rear = 4;                
    int arraySize = 20;                // Size of the array
    int N = 3;                    // Number of steps
    char ch;
    for(int i = 0;i < N;++i) {
        ch = Front(queue, front);
        enqueue(queue, ch, rear, arraySize);
        dequeue(queue, front, rear);
    }
    for(int i = front;i < rear;++i)
        printf("%c", queue[i]);
    printf("\n");
    return 0;
}

For any queries comment below 

Comments