zoukankan      html  css  js  c++  java
  • Leetcode 232 Implement Queue using Stacks STL

    本题用两个栈实现队列,用栈的基本操作去实现队列的所有基本操作push(),pop(),peek()以及empty()

    sa作为输入栈,sb作为输出栈,将sa输入元素的反转过来放到sb中

    push与sa有关,而pop(),peek()与sb有关,即将sa输入元素出栈放到sb中(函数move).

    为此,只有两个栈为空才能让队列为空

     1 class Queue {
     2 public:
     3     // Push element x to the back of queue.
     4     stack<int> sa;
     5     stack<int> sb;
     6     void move(){
     7         while(!sa.empty()){
     8             sb.push(sa.top());
     9             sa.pop();
    10         }
    11     }
    12     void push(int x) {
    13         sa.push(x);
    14     }
    15 
    16     // Removes the element from in front of queue.
    17     void pop(void) {
    18         if(!sb.empty()) sb.pop();
    19         else{
    20             move();
    21             sb.pop();
    22         }
    23     }
    24 
    25     // Get the front element.
    26     int peek(void) {
    27         if(!sb.empty()) return sb.top();
    28         else{
    29             move();
    30             return sb.top();
    31         }
    32 
    33     }
    34 
    35     // Return whether the queue is empty.
    36     bool empty(void) {
    37         return sa.empty() && sb.empty();
    38     }
    39 };
  • 相关阅读:
    [SHOI2015]脑洞治疗仪
    [SDOI2016]数字配对
    [SDOI2019]快速查询
    [HNOI2019]JOJO
    [TJOI2019]甲苯先生和大中锋的字符串
    [CQOI2017]老C的方块
    [CQOI2017] 小Q的表格
    [SHOI2012] 火柴游戏
    板子
    自我介绍
  • 原文地址:https://www.cnblogs.com/onlyac/p/5232161.html
Copyright © 2011-2022 走看看