# Data Structure: Implementation of Queue in C++

A queue is an order collection of items from which items may be deleted at one end (called front or head of the queue) and into which items may be inserted at the other end (called the rear end or tail of the queue). It is First-in-First-out (FIFO) type of data structure. Operations on the queue are: Create a Queue, insert items, remove items, display etc.
Please refer to this link for a more detailed explanation of queue and its implementation in C, C++, Python, and Java.
Algorithm for Implementation of Queue in C++
1. Declare and initialize neccessary variables, front = 0, rear = -1 etc.
2. For enque operation,
If rear >= MAXSIZE – 1
print “Queue is full”
Else
– Increment rear by 1 i.e. rear = rear + 1;
– queue[rear] = item;
3. For next enqueue operation, goto step 2.
4. For dequeue operation
If front > rear
print “Queue is Empty”
Else
– item = queue[front]
– increment front by 1 i.e. front = front + 1
5. For dequeue next data items, goto step 4.
6. Stop

Source Code:

#include<iostream>

#include<cstdlib>

#define MAX_SIZE 10

using namespace std;

class Queue{

private:

int item[MAX_SIZE];

int rear;

int front;

public:

Queue();

void enqueue(int);

int dequeue();

int size();

void display();

bool isEmpty();

bool isFull();

};

Queue::Queue(){

rear = -1;

front = 0;

}

void Queue::enqueue(int data){

item[++rear] = data;

}

int Queue::dequeue(){

return item[front++];

}

void Queue::display(){

if(!this->isEmpty()){

for(int i=front; i<=rear; i++)

cout<<item[i]<<endl;

}else{

cout<<"Queue Underflow"<<endl;

}

}

int Queue::size(){

return (rear - front + 1);

}

bool Queue::isEmpty(){

if(front>rear){

return true;

}else{

return false;

}

}

bool Queue::isFull(){

if(this->size()>=MAX_SIZE){

return true;

}else{

return false;

}

}

int main(){

Queue queue;

int choice, data;

while(1){

cout<<"\n1. Enqueue\n2. Dequeue\n3. Size\n4. Display all element\n5. Quit";

cin>>choice;

switch(choice){

case 1:

if(!queue.isFull()){

cout<<"\nEnter data: ";

cin>>data;

queue.enqueue(data);

}else{

cout<<"Queue is Full"<<endl;

}

break;

case 2:

if(!queue.isEmpty()){

cout<<"The data dequeued is :"<<queue.dequeue();

}else{

cout<<"Queue is Emtpy"<<endl;

}

break;

case 3:

cout<<"Size of Queue is "<<queue.size();

break;

case 4:

queue.display();

break;

case 5:

exit(0);

break;

}

}

return 0;

}
SHARE Data Structure: Implementation of Queue in C++

### 5 Responses

1. Anonymous says:

this program is not excuteable on the quincy

2. Anonymous says:

(Used the given source code)
After I enqueued data, I dequeued and then enqueued a new one. Then select Display all elements. The last data dequeued was added at the bottom of the list. Is this an error on the code?
p.s.
I'm new to programming.

3. Thank you you make my work even better. This program is worthy.