1. 程式人生 > >劍指offer____用兩個棧實現佇列

劍指offer____用兩個棧實現佇列

用兩個棧來實現一個佇列,完成佇列的Push和Pop操作。 佇列中的元素為int型別。

class Solution
{
public:
    //佇列的特點是先進先出,棧的特點是後進先出
    void push(int node)
    {
         s1.push(node);
    }
      

    int pop() 
    {
        int result = -1;
        if(!s2.empty())
        {
            result = s2.top();
            s2.pop();
        }
        else
        {
            if(s1.empty()) return -1;
            while(!s1.empty())
            {
                s2.push(s1.top());
                s1.pop();
            }
            result = s2.top();
            s2.pop();
        }
        return result;
    }

private:
    stack<int> s1;
    stack<int> s2;
};