232. 用栈实现队列

65 阅读1分钟

232. 用栈实现队列 - 力扣(LeetCode)

要求用栈模拟实现队列。

栈的特性:先进后出 队列的特性:先进先出

把一个队列里的值倒入另一个队列里面,原来的先就变为了后

因此可以用两个队

class MyQueue {
public:  
  stack<int> s1;
    stack<int> s2;
    MyQueue() {

    }
    
    void push(int x) {
    
      s1.push(x);
    }
    
    int pop() {
             
      if(s2.empty())
      {while(!s1.empty())
      {
            s2.push(s1.top());
            s1.pop();
      }
         }       
            int result=s2.top();
            s2.pop();
            return result;
    }
    
    int peek() {
         int res = this->pop(); // 直接使用已有的pop函数
        s2.push(res); // 因为pop函数弹出了元素res,所以再添加回去
        return res;

    }
    
    bool empty() {
     
     return s2.empty()&&s1.empty();
    }
};