What is queue in data structure?

A Queue is a linear structure which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added. The time complexity of queue is O(1)

There are two types of queue.

  • Linear Queue
  • Circular Queue

In this tutorial ,I’ll show you how to implement Circular queue in array using C++.

Well, We know queue is a restrictive data structure which have two main function one is enqueue another one is dequeue. Using enqueue function we insert data in queue and using dequeue we return or remove data from queue. We’ll see everything step by step.

Set Initial Values and Function :

int queue[size];

int i,front,rear;

void initial()
{
    front = rear = -1;
}

Code for enqueue :

void enqueue(int val)
{
    if(front == -1 && rear == -1)
    {
        front = rear = 0;
        queue[rear] = val;
        cout<<"Successfully insert\n";
    }
    else if ((rear+1)%size == front)
    {
        cout<<"\nQueue is full";
    }
    else{
        rear = (rear+1)%size;
        queue[rear] = val;
        cout<<"Successfully insert\n";
    }
}

Code For Display Data :

void display()
{
    if(front == -1 && rear == -1)
    {
        cout<<"\nQueue is empty";
    }
    else{
        cout<<"\nQueue data : ";
        int i = front;
        while(i!=rear)
        {
            cout<<queue[i]<<" ";
            i = (i+1)%size;
        }
        cout<<queue[rear];
    }
}

Code For Dequeue Function :

void dequeue()
{
    if(front == -1 && rear == -1)
    {
        cout<<"\nQueue is empty";
    }
    else if(front == rear)
    {
        cout<<"\nDequeue data : ";
        cout<<queue[front];
        front = rear = -1;

    }
    else{
        cout<<"\nDequeue data : ";
        int x = queue[front];
        cout<<x;
        front = (front+1)%size;
    }
}

Now Call those functions in your main function :

int main()
{
    initial();
    enqueue(10);
    enqueue(20);
    enqueue(30);
    display();
    dequeue();
    return 0;
}

GitHub link : https://github.com/AR-Shahin/Data_Structure_and_Algorithm/blob/main/Queue/circuler_queue_cpp.txt

If you have any question regarding this tutorial you can comment here.

3 thoughts on “What is queue in data structure?”

  1. Pingback: How to implement Queue using Link List? – Shahin's Blog

Leave a Comment

Your email address will not be published. Required fields are marked *