zoukankan      html  css  js  c++  java
  • 232. Implement Queue using Stacks(队列实现栈)

    请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):

    实现 MyQueue 类:

    void push(int x) 将元素 x 推到队列的末尾
    int pop() 从队列的开头移除并返回元素
    int peek() 返回队列开头的元素
    boolean empty() 如果队列为空,返回 true ;否则,返回 false
     

    说明:

    你只能使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
    你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

     

     1 class MyQueue {
     2 private:
     3     stack<int> s1;
     4     stack<int> s2;
     5 public:
     6     /** Initialize your data structure here. */
     7     MyQueue() {
     8 
     9     }
    10     
    11     /** Push element x to the back of queue. */
    12     void push(int x) {
    13         s2.push(x);
    14     }
    15     
    16     /** Removes the element from in front of queue and returns that element. */
    17     int pop() {
    18         int v = peek();
    19         s1.pop();
    20         return v;
    21     }
    22     
    23     /** Get the front element. */
    24     int peek() {
    25         if(s1.empty()) {
    26             while(!s2.empty()) {
    27                 s1.push(s2.top());
    28                 s2.pop();
    29             }
    30         }
    31         return s1.top();
    32     }
    33     
    34     /** Returns whether the queue is empty. */
    35     bool empty() {
    36         return s1.empty() && s2.empty();
    37     }
    38 };
    39 
    40 /**
    41  * Your MyQueue object will be instantiated and called as such:
    42  * MyQueue* obj = new MyQueue();
    43  * obj->push(x);
    44  * int param_2 = obj->pop();
    45  * int param_3 = obj->peek();
    46  * bool param_4 = obj->empty();
    47  */
  • 相关阅读:
    [USACO06NOV]Corn Fields(状压DP)
    关灯问题II (状态压缩 BFS)
    天梯---至多删三个字符(DP)
    天梯
    蓝桥
    天梯
    天梯
    天梯
    天梯
    蓝桥
  • 原文地址:https://www.cnblogs.com/zle1992/p/14825224.html
Copyright © 2011-2022 走看看