Exercises on stacks and queues [2]

Ideas:

1. Only the head of the queue can be taken out, so it can only be taken out when the last element inserted is the head;

2. Another queue is stored as a removed element

Class MyStack
{
public:

        queue<int>q1;
        queue<int>q2;
        MyStack(){}
        void push(int x){q1.push(x)};
        int pop(){
            while(q1.size()!=1)
            {
                q2.push(q1.front());
                q1.pop();
            }
            int data =q1.front();
            q1.pop();
            q1=q2;
            while(!q2.empty())
            {
                q2.pop();
            }
            return data;
        }
        int top()
        {
            return q1.back();
        }
        bool empty()
        {
            return q1.empty();
         }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324133838&siteId=291194637
Recommended