Friday, August 31, 2012

C Program for Circular Queue

#include<iostream.h>
#include<process.h>
#include<conio.h>
class queue
{
  int x[10],rear,front,i,t;
  public:
  queue()
  {
   front=-1;
   rear=-1;
   for(int i=0;i<10;i++)
   x[i]=0;
  }
  void push(int y)
  {
   if((front==0&&rear==9)||(front==rear+1))
   {
       cout<<"Overflow";
       return;
   }
   if(rear==9)
    rear=0;
   else
    rear++;
   x[rear]=y;
   if(front==-1)front=0;
 }
  int pop()
  {
   if((front==-1))
   {
       cout<<"Underflow";
       return NULL;
   }
   t=x[front];
   x[front]=0;
   if(rear==front)
   front=rear=-1;
   else
   {
    if(front==9)
      front=0;
     else
      front++;
   }
   return t;
  }
  void show()
  {
    if(front==-1&&rear==-1)return;
    if(front<=rear)
    {
     for(int i=front;i<=rear;i++)
     cout<<" "<<x[i];
    }
    else
    {
     i=front;
     while(i!=rear)
     {
      cout<<" "<<x[i];
      i++;
      if(i==10)
      i=0;
     }
    }
  }
  void process()
  {
    clrscr();
    while(1)
    {
//      clrscr();
      cout<<"\nEnter Choice\n 1.PUSH  2.POP  3.Exit";
      char ch;
      int t;
      ch=getche();
      switch(ch)
      {
    case '1':
    cout<<"\nEnter no.:";
    cin>>t;
    push(t);
    cout<<"Elements in Queue.:";
    show();
    break;
    case '2':
    t=pop();
    cout<<"\nElement POPED.:"<<t;
    cout<<"\nElements in Queue.:";
    show();
    break;
    default:
    exit(0);
     }
     getch();
    }
  }
};
void main()
{
  queue q;
  q.process();
}

No comments:

Post a Comment