Insertion in a Queue in C++

Insertion in a Queue in C++

 

Queue is  a data structure where you can insert elements in First in First out manner, so you can store values in order to they are coming in a structure. This basic data structure has two major properties, enqueue and dequeue. In this particular article, we will find how to insert elements in a queue in C++, i.e. Enqueueing elements. Here we will use OOps Concept and List prebuilt structure.

Insertion in a Queue in C++ | PrepInsta
Enqueue in a Queue in C++

What is Queue?

 
Queue is a standard linear user defined data structure that allows you to pre-store  elements in the specific order it gets, as get a first in first out or FIFO feature in that.
 

To Know more about Queue : Queue in C++ STL

 

Best Queue

The Agorithm to insert in Queue : Enqueue

Here goes the following algorithm that tells us how to enqueue / Insert elements in a queue.

  • Let’s say the queue is a linked list. Here we have used a predefined linkedlist that is available inside C++ standard template library (List in STL), and made a class where there is a member variable of that type.
  • Now Queue is first in first out. So the pushes will be at back of the list. You can obtain that in a different way, in C too : Here it is.
  • That means, if queue is empty, we will simply push that element into it.
  • Otherwise we will make a place at the back and add the element there.
Enqueue in S

The code to implement this:

#include<bits/stdc++.h>
using namespace std;

class Queue
{
  public:
  list<intL;
  void Push(int i)
  {
    cout<<“Pushing the element : “<<(i)<<endl;
    L.push_back(i);
  }
  int pop()
  {
    if(L.empty()) {cout<<“The queue is empty”<<endl;}
    int a=L.front();
    L.pop_front();
    return a;
  }
  void Show()
  {
    for(auto i:L)
    cout<<i<<” “;
    cout<<endl;
  }
};

int main()
{
  Queue q;
  q.Push(2);q.Push(9);q.Push(3);
  q.Push(5);q.Push(12);q.Push(1);
  q.Show();
}
 

Output:

Pushing the element : 2
Pushing the element : 9
Pushing the element : 3
Pushing the element : 5
Pushing the element : 12
Pushing the element : 1
2 9 3 5 12 1 

Article is contributed by Rahit Saha