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

    主要思想:

    申请两个辅助栈,一个用于进in,一个用于出out,倒腾一之后,在出之前变为FIFO即是队列

     1 class Queue {
     2     stack<int> in,out;
     3 public:
     4     // Push element x to the back of queue.
     5     void push(int x) {
     6         in.push(x);
     7     }
     8 
     9     // Removes the element from in front of queue.
    10     void pop(void) {
    11         checkOut();
    12         out.pop();
    13     }
    14 
    15     // Get the front element.
    16     int peek(void) {
    17         checkOut();
    18         return out.top();
    19         
    20     }
    21 
    22     // Return whether the queue is empty.
    23     bool empty(void) {
    24         if(in.empty()&&out.empty())
    25             return true;
    26         return false;
    27     }
    28     void checkOut()
    29     {
    30         if(out.empty())
    31         {
    32             while(!in.empty())
    33             {
    34                 out.push(in.top());
    35                 in.pop();
    36             }
    37         }
    38     }
    39 };
  • 相关阅读:
    Linux
    Linus
    Linux
    Linux
    Linux
    Linux
    Linux
    Linux
    Django日志配置
    linux
  • 原文地址:https://www.cnblogs.com/aguai1992/p/4628619.html
Copyright © 2011-2022 走看看