Untitled

mail@pastecode.io avatar
unknown
c_cpp
7 months ago
1.5 kB
0
Indexable
Never
#include <iostream>
#include <stdlib.h>
using namespace std;
// program for circular queue
int q[5];
int sz=5;;
int front=-1,rear=-1;
void push(int val)
{
    if(front==-1)
    {
        front=rear=0;
        q[rear]=val;
    }else
    {
        int t=(rear+1)%sz;
        if(t==front)
        {
            cout<<"q is full"<<endl;
        }else
        {
            rear=(rear+1)%sz;
            q[rear]=val;
        }
    }
}
void pop()
{
    if(front==-1)
    {
        cout<<"q is empty"<<endl;
    }else
    {
        if(front==rear)
        {
            cout<<"q is empty"<<endl;
            front=rear=-1;
        }else
        {
            front=(front+1)%sz;
        }
        
    }
    
}
void display()
{
    if(rear==-1)
    {
        cout<<"no items"<<endl;
        return;
    }
    if(front<=rear)
    {
        for(int i{front};i<=rear;i++)
        {
            cout<<q[i]<<" ";
        }
        cout<<endl;
    }else
    {
        for(int i{front};i<sz;i++)
        {
            cout<<q[i]<<" ";
        }
        for(int i{0};i<=rear;i++)
        {
            cout<<q[i]<<" ";
        }
        cout<<endl;
    }
}
int main()
{
    push(1);
    push(2);
    push(3);
    push(4);
    display();
    pop();
    pop();
    pop();
    display();
    push(1);
    push(2);
    push(3);
    push(4);
    display();
    push(1);
    push(1);
    push(1);
    display();
    pop();
    pop();
    pop();
    pop();
    pop();
    display();
    
    
}
Leave a Comment