【Leetcode】232. Implement Queue using Stacks

题目地址:

https://leetcode.com/problems/implement-queue-using-stacks/

用栈来模拟队列。

可以用两个栈,一个模拟队列头,一个模拟队列尾。队尾的那个栈专门用来enqueue,队列头的那个栈专门用来dequeue。当dequeue的那个栈空了,就将enqueue里所有元素都倒进dequeue里去,这样顺序就再次反了一下,就变成FIFO了。代码如下:

class MyQueue {
 public:
  stack<int> stk, stk0;
  MyQueue() {}

  void push(int x) { stk.push(x); }

  int pop() {
    if (stk0.empty()) {
      while (stk.size()) {
        stk0.push(stk.top());
        stk.pop();
      }
    }
    int res = stk0.top();
    stk0.pop();
    return res;
  }

  int peek() {
    if (stk0.empty()) {
      while (stk.size()) {
        stk0.push(stk.top());
        stk.pop();
      }
    }
    return stk0.top();
  }

  bool empty() { return stk.empty() && stk0.empty(); }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

时间复杂度:push: O ( 1 ) O(1) O(1),pop和peek:均摊 O ( 1 ) O(1) O(1)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值