代码随想录Day10-栈和队列

78 阅读1分钟

Day10-栈和队列

用栈实现队列

把两个栈倒来倒去地解决了,这显然是比较愚笨的做法

class MyQueue {
 public:
  MyQueue() {
​
  }
​
  void push(int x) {
    a.push(x);
  }
​
  int pop() {
    change();
    int ret = b.top();
    b.pop();
    change();
    return ret;
  }
​
  int peek() {
    change();
    int ret = b.top();
    change();
    return ret;
  }
​
  bool empty() {
    return a.empty();
  }
​
  std::stack<int> a;
  std::stack<int> b;
  
 private:
  void change(){
    if(!a.empty()){
      while(!a.empty()) {
        int tmp = a.top();
        a.pop();
        b.push(tmp);
      }
    }else{
      while(!b.empty()){
        while(!b.empty()){
          int tmp = b.top();
          b.pop();
          a.push(tmp);
        }
      }
    }
  }
};

设置输出栈输入栈

完成本题

用队列实现栈

class MyStack {
    public:
    MyStack() {
​
    }
​
    void push(int x) {
      queue_.push(x);
    }
​
    int pop() {
      int ret;
      int len = queue_.size();
      for(int i = 0; i < len; i++){
        ret = queue_.front();
        queue_.pop();
        if(i != len - 1) queue_.push(ret);
      }
      return ret;
    }
    
    int top() {
      int ret;
      for(int i = 0; i < queue_.size(); i++){
        ret = queue_.front();
        queue_.pop();
        queue_.push(ret);
      }
      return ret;
    }
​
    bool empty() {
      return queue_.empty();
    }
​
    private:
    queue<int> queue_;
​
};

利用单队列完成队列实现栈的转化