【leetcode/栈】用栈实现队列

问题描述:

RTRT

基本思路:

  1. 由于栈的出入顺序是相反的,而队列的顺序是相同的。负负得正嘛。我们不妨用两个栈来实现
  2. 队列中有两个栈,其中一个用于模拟入队,另一个用于模拟出队。两个栈的所有元素构成我们队列中的元素。当模拟出队的栈空间不够的时候,我们就把入队栈中所有的元素全部倒入出队栈。
  3. 当然我们可以用链表啥的来实现,不过这种实现方法每次取队首元素是都要遍历全表。而我们的方法只是在出队栈为空的时候才要这么做。其他时间都是O(1)。

AC代码:

#include<bits/stdc++.h>
using namespace std;

class MyQueue {
 private:
  stack<int> in;
  stack<int> out;

 public:
  void FetchFromOut() {
  // 把in中的元素全部转移给out
    while (!in.empty()) {
      int t = in.top();
      in.pop();
      out.push(t);
    }
  }

  void push(int x) { in.push(x); }
  int pop() {
    if (out.empty()) {
      FetchFromOut();
    }
    int ret_val = out.top();
    out.pop();
    return ret_val;
  }
  int peek() {
    if (out.empty()) {
      FetchFromOut();
    }
    return out.top();
  }
  bool empty() { return in.empty() && out.empty(); }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值