Tuesday, October 21, 2014

Using Template in C++, implement queue data structure

#include<iostream.h>
#define size 100
template <class T>
class queue
{
    private:   
          T item[size];
        int front,rear;
    public:
                queue()
                {
                  rear=-1;

                  front=0;
                }
                void insert(T x)
                {
                      if(rear==size-1)
                     cout<<"\nOVERFLOW";
                     else
                     item[++rear]=x;
                }
                T remove1()
                {
                    if(rear<front)
                    {
                            cout<<"\nQUEUE UNDERFLOW";
                            return 0;
                    }
                    else
                        return(item[front++]);
                }

            void display()
                {
                     int k;
                     cout<<"\nOUTPUT==>>";
                     if(rear<front)
                     {
                             cout<<"\tQUEUE UNDERFLOW";
                     }
                     else
                     {
                             for(k=front;k<=rear;k++)
                             cout<<"\t"<<item[k];
                        }
                }
};

void main()
{
     int i;
     queue<int> q; //insert char, float, double elements to change here
                        //type of the varibale
    while(1)
    {
          cout<<"\nPress 1 for enter integer=";
          cout<<"\nPress 2 for remove=";
          cout<<"\nPress 3 for display=";
          cout<<"\nEnter Choice=";
          cin>>i;
        cout<<"\n\n\t\t\t\t<<==LINEAR QUEUE==>>\n";
        switch(i)
          {
                case 1:  int j;   //insert char, float, double
                                        //elements to change here
                                        //type of the varibale

                            cout<<"\nEnter element=";
                            cin>>j;
                            q.insert(j);
                            break;
                case 2:     cout<<"\nThe remove element is="<<q.remove1();
                             break;
                case 3:     q.display();
                            break;
            default:    cout<<"\n\bWRONG CHOICE";
        }
     }

}

No comments:

Post a Comment