[Data structure and algorithm] Two stacks to achieve a queue

Topic Description
Use two stacks to implement a queue and complete Push and Pop operations on the queue. The elements in the queue are of type int.

#include <iostream>
#include <stack>
using namespace std;

class Solution{
public:
    void push(int num)
    {
        in.push(num);
    }
    int pop()
    {
        int ret;

         if(!out.empty())
        {
            ret=out.top();
            out.pop();
            return ret;
        }
      
       
        while(!in.empty())
        {
            out.push(in.top());
            in.pop();
        }

        ret=out.top();
        out.pop();

       return ret;

    }
private:
    stack<int>  in;
    stack<int>  out;

};

int main()
{
    Solution so;
    for (int i=0;i<5;i++)
    {
        so.push(i);
    }
    
    for(int i=0;i<5;i++)
    {
        int r=so.pop();
        cout<<"pop------->"<<r<<endl;
    }
    return 0;
}
Published 19 original articles · Likes0 · Visits 383

Guess you like

Origin blog.csdn.net/qinchun/article/details/105353334