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 };
  • 相关阅读:
    【JavaScript】--ajax
    【Django】--Models 和ORM以及admin配置
    【Django】--基础知识
    【jQuery】--图片轮播
    双系统 windows引导项添加
    LVM
    linux安全加固
    oracle 11G 配置侦听文件
    LVM
    《virtual san 最佳实践》节选 Virtual SAN的发展与现状
  • 原文地址:https://www.cnblogs.com/onlyac/p/5259820.html
Copyright © 2011-2022 走看看