zoukankan      html  css  js  c++  java
  • Leetcode 225 Implement Stack using Queues STL

    用两个队列去实现栈,这里我使用了队列数组q[2],在所有的过程中保证一个队列是空的

    push时插入到空的队列中,然后将队列中的元素移到另一个队列中

    pop时从不空的队列中pop()

    peek时从不空的队列中取出front()

     1 class Stack {
     2 public:
     3     queue<int> q[2];
     4     
     5     // Push element x onto stack.
     6     void move(int x){
     7         while(!q[1-x].empty()){
     8             q[x].push(q[1-x].front());
     9             q[1-x].pop();
    10         }
    11     }
    12     
    13     void push(int x) {
    14         for(int i = 0; i < 2; ++i){
    15             if(q[i].empty()){
    16                 q[i].push(x);
    17                 move(i);
    18                 break;
    19             }
    20         }
    21     }
    22 
    23     // Removes the element on top of the stack.
    24     void pop() {
    25         for(int i = 0; i < 2; ++i){
    26             if(!q[i].empty()){
    27                 q[i].pop();
    28                 break;
    29             }
    30         }
    31     }
    32 
    33     // Get the top element.
    34     int top() {
    35         for(int i = 0; i < 2; ++i){
    36             if(!q[i].empty()){
    37                 return q[i].front();
    38             }
    39         }
    40     }
    41 
    42     // Return whether the stack is empty.
    43     bool empty() {
    44         return q[0].empty() && q[1].empty();
    45     }
    46 };
  • 相关阅读:
    jQuery$命名冲突问题解决方法
    微信小程序开发工具 ubuntu linux版本
    阿里云Https通配符证书购买
    vs2017安装
    规范与标准
    Jvm远程监控
    Bash笔记
    Html5前端笔记
    Php7 开发笔记
    webpack笔记
  • 原文地址:https://www.cnblogs.com/onlyac/p/5259820.html
Copyright © 2011-2022 走看看