zoukankan      html  css  js  c++  java
  • LeetCode 232 Implement Queue using Stacks 两个栈实现队列

     1 class MyQueue {
     2 public:
     3     /** Initialize your data structure here. */
     4     MyQueue() {
     5         
     6     }
     7     
     8     /** Push element x to the back of queue. */
     9     void push(int x) {
    10         stkPush.push(x);
    11     }
    12     
    13     /** Removes the element from in front of queue and returns that element. */
    14     int pop() {
    15         int val;
    16         if(stkPop.empty())
    17         {
    18             while(!stkPush.empty())
    19             {
    20                 val=stkPush.top();
    21                 stkPush.pop();
    22                 stkPop.push(val);
    23             }
    24         }
    25         val=stkPop.top();
    26         stkPop.pop();
    27         return val;
    28     }
    29     
    30     /** Get the front element. */
    31     int peek() {
    32         if(stkPop.empty())
    33         {
    34             while(!stkPush.empty())
    35             {
    36                 int val=stkPush.top();
    37                 stkPush.pop();
    38                 stkPop.push(val);
    39             }
    40         }
    41         return stkPop.top();
    42     }
    43     
    44     /** Returns whether the queue is empty. */
    45     bool empty() {
    46         return stkPush.empty()&&stkPop.empty();
    47     }
    48 private:
    49     stack<int> stkPush;
    50     stack<int> stkPop;
    51 };
    52 
    53 /**
    54  * Your MyQueue object will be instantiated and called as such:
    55  * MyQueue obj = new MyQueue();
    56  * obj.push(x);
    57  * int param_2 = obj.pop();
    58  * int param_3 = obj.peek();
    59  * bool param_4 = obj.empty();
    60  */
  • 相关阅读:
    Mockito
    输入一个链表,输出该链表中倒数第k个结点。
    序列化
    全排列
    PostgreSQL libpq学习指南二
    PostgreSQL libpq 客户端接口(一)
    PostgreSQL 中的shared buffer
    通过 Unwrapper 解密 DBMS 程序包
    openGuassDB介绍及安装实践
    PostgreSQL中的ACID特性介绍
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8534593.html
Copyright © 2011-2022 走看看