How to insert and remove values from queue in C++

A queue is a data structure in which element inserted at first will be removed at first.Queue is opposite data structure of stack.For example a waiting line can be considered as a queue.The person at front of queue will be treated at first, and person at last will be treated at last.In the same way, in programming when we implement queue structure, then element added first will be removed first and element added at last will be removed at last.
There are two methods that are used to push and pop values from the queue.These methods are explained below.

Enqueue Method:
This method is used to insert values at the end of  queue.A queue may be an array or some linked list.This method will also check for being overflowing of queue.It means it will check whether queue is full or not.If queue is full and user tries to input a value then overflow will be occur.

Dequeue Method
This method is used to get values from the queue.It will also check for underflow.The underflow occurs when user tries to fetch value from index that is not available in queue like -1.

So I hope you understand basic concept about queue.Now copy the following code, paste it in editor and see magic. 


#include <iostream>
#include<conio.h>
using namespace std;
int a[3];
int botm;
int top=botm=-1;

void enqueue(){
 if(top==2){
  cout<<"overflow";
 }
 else{
  int b;
   cout<<"enter value for enqueue=";
  cin>>b;
 top = top + 1;
    a[top] = b;
        int i;
    cout<<"Stack: \n";
    for (i=top;i>=0;i--)
    {
        cout<<a[i];
        cout<<"\n";
    }
}}
void dequeue()
{if(top==botm){
 top=botm=-1;
}
    if(top == -1)
    {
        cout<<"Error: there is no element to pop"<<endl;
        return;
    }
    
       botm++;
           int i;
    cout<<"Stack: \n";
    for (i=top;i>botm;i--)
    {
        cout<<a[i];
        cout<<"\n";
    }
    
}
int main(){
 aw:
int a;
 cout<<"1.enter for enqueue \n2. for dequeue"<<endl;
 cin>>a;
 switch(a){
  case 1:
 {
 
 enqueue();
 cout<<endl;  
 cout<<"after push value of TOP="<<top<<endl;
 break;}
 case 2:
  {
   
  dequeue();
  cout<<"after pop value of botom="<<botm<<endl; 
 break; }
 }
 goto aw;
getch();
}




Reactions

Post a Comment

0 Comments