• Implement Stack using Queues


     1 class Stack {
     2 public:
     3     // Push element x onto stack.
     4     void push(int x) {
     5         if(q1.empty()&&q2.empty())
     6         q1.push(x);
     7         else 
     8         {
     9             if(q1.empty())
    10             q2.push(x);
    11             else q1.push(x);
    12         }
    13         
    14     }
    15 
    16     // Removes the element on top of the stack.
    17     void pop() {
    18          if(q1.empty()&&q2.empty())
    19          return ;
    20          else 
    21          {
    22              if(q1.empty())
    23              {
    24                  if(q2.size()==1)
    25                  q2.pop();
    26                  else
    27                  {
    28                      while(q2.size()>1)
    29                      {
    30                          q1.push(q2.front());
    31                          q2.pop();
    32                      }
    33                      q2.pop();
    34                  }
    35              }
    36              else
    37              {
    38                   if(q1.size()==1)
    39                  q1.pop();
    40                  else
    41                  {
    42                      while(q1.size()>1)
    43                      {
    44                          q2.push(q1.front());
    45                          q1.pop();
    46                      }
    47                      q1.pop();
    48                  }
    49              }
    50              }
    51          }
    52     
    53 
    54     // Get the top element.
    55     int top() {
    56          if(q1.empty()&&q2.empty())
    57          return -1;
    58          else 
    59          {
    60              if(q1.empty())
    61              {
    62                  return q2.back();
    63              }
    64              else
    65              {
    66                  return q1.back(); 
    67              }
    68              }
    69          }
    70     
    71 
    72     // Return whether the stack is empty.
    73     bool empty() {
    74         if(q1.empty()&&q2.empty())
    75         return true;
    76         else return false;
    77     }
    78 private:
    79    queue<int> q1;
    80    queue<int> q2;
    81 };
  • 相关阅读:
    SP1812 LCS2
    SP1811 LCS
    P3804 【模板】后缀自动机
    P3808 【模板】AC自动机(简单版)
    P3879 [TJOI2010]阅读理解
    P2602 [ZJOI2010]数字计数
    P4719 【模板】动态dp
    P1122 最大子树和
    P3554 [POI2013]LUK-Triumphal arch
    P3565 [POI2014]HOT-Hotels
  • 原文地址:https://www.cnblogs.com/daocaorenblog/p/5440371.html
Copyright © 2020-2023  润新知