Search This Blog

Tuesday 2 February 2016

Stack - Queue Implementation using class C++

//implement stack-queue such that
//insert() - push item in stack
//pop() - pop elements from stack and insert into queue
//display() - display the queue

#include<iostream>
#include<stdio.h>

using namespace std;

class SQ
{
    int rear,front,top,stack[5],queue[5];
    public:
    int full();
    int empty();
    void set();
    void insert(int);
    void pop();
    void display();
};
int SQ::full()
{
    if(rear==4 || top==4)
    return 1;
    else
    return 0;
}
int SQ::empty()
{
    if(top==-1)
    return 1;
    else
    return 0;
}
void SQ::set()
{
    rear=-1;
    front=0;
    top=-1;
}
void SQ::insert(int i)
{
    stack[++top]=i;
}
void SQ::display()
{
       /*    cout<<"\nStack is:"<<endl;

    for(int i=top;i>=0;i--)
    {
        cout<<"\n";
        cout<<stack[i];                                          // if you want to see the stack
    }
    cout<<"\n";
    */
    if(rear==-1)
    {
        cout<<"\nPop Element from stack to insert in queue"<<endl;
    }
    else{
    cout<<"\nQueue is:"<<endl;
    for(int j=front;j<=rear;j++)
    {

        cout<<queue[j]<<" ";
    }
    cout<<"\n";
    }

}
void SQ::pop()
{
    /*if(top==-1)
    {
        cout<<"\nDone"<<endl;
    } */
    if(rear==-1){
    queue[++rear]=stack[top];
    top--;
    }else
    {
        queue[++rear]=stack[top];
        top--;
    }

}
int main()
{
    SQ sq;
    sq.set();
    int ch,val;
    do
    {
        cout<<"\nEnter your choice:\n1.insert into stack\n2.pop from stack and push into queue\n3.display\n4.enter 0 to exit"<<endl;
        cin>>ch;

        switch(ch)
        {
            case 1:if(sq.full())
            {
                cout<<"\nFull!"<<endl;
            }
            else
            {cout<<"\nEnter ele:";
            cin>>val;
            sq.insert(val);
            }
            break;

            case 2:if(sq.empty())
            {
                cout<<"\nEmpty"<<endl;
            }else
            {
                sq.pop();
            }
            break;

            case 3:sq.display();
            break;


            default:cout<<"\nEnter Proper choice"<<endl;
        }
    }while(ch!=0);
    return 0;
}

No comments:

Post a Comment