C++: Implementation of Queue using Array (Data Structure)

I have studied the algorithm for implementation of Queue from Introduction to Algorithm.
Queue is one of the elementary data structure. And as I had said earlier to learn programming we have understand Data Structure and Algorithm. Any programming language is just a tool to solve a problem.


It is a Dynamic set. Dynamic sets are sets which can be manipulated by algorithms, which can grow, shrink or change over time.

➧ It implements first-in,first-out means element which is entered last in the stack will be on the top of the stack thus will be deleted first. [FIFO]

➧ To insert an element we call ENQUEUE operation and to delete an element we call DEQUEUE operation.

➧ It has head and tail. When an element is enqueued, it takes place its place at the tail of the queue and the element dequeued is always the one at the head of the queue.

➧ Q[Q.head, Q.head+1, ..., Q.tail-1]. The Q.tail indexes the next location at which a newly arriving element will be inserted into the queue.

➧ When Q.head=Q.tail, the queue is empty. Initially, Q.head=Q.tail=1. When Q.head=Q.tail+1, the queue is full.

#include <iostream>
#define max 1000
class Queue{int head,tail;public:    int a[max];    Queue(){    head=0;    tail=0;    }  void enqueue(int x);  int dequeue();  void display();};
void Queue::enqueue(int x){a[tail]=x;if( tail+1==(max-1))    tail=0;else    tail++;}
int Queue::dequeue(){int x=a[head];if(head==(max-1))    head=0;else    head++;return x;}
void Queue::display(){for(int i=head;i<tail;i++){    std::cout<<a[i]<<" ";}}int main(){    Queue queue1;    queue1.enqueue(15);    queue1.enqueue(6);    queue1.enqueue(9);    queue1.enqueue(8);    queue1.enqueue(4);    queue1.enqueue(41);    queue1.enqueue(42);    queue1.enqueue(43);    queue1.display();    std::cout<<"\n"<<queue1.dequeue()<<"\n";    queue1.display();    return 0;}

Here array starts from 1.

Now should also read C++: Queue implementation using Linked List (Data Structure)  

 Follow us on


You may also like:

C++: STL Iterators
C++: Implementation of Quicksort (Sorting)
C++: Insertion Sort using STL (Sorting)
Which Linux distribution is the best for a programmer?
How do I improve my logical thinking and problem solving skills?