zoukankan      html  css  js  c++  java
  • 225. Implement Stack using Queues (栈实现队列)

    请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(push、top、pop 和 empty)。

    实现 MyStack 类:

    void push(int x) 将元素 x 压入栈顶。
    int pop() 移除并返回栈顶元素。
    int top() 返回栈顶元素。
    boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
     

    注意:

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

     1 class MyStack {
     2 private: queue<int> q;
     3 public:
     4     /** Initialize your data structure here. */
     5     MyStack() {
     6 
     7     }
     8     
     9     /** Push element x onto stack. */
    10     void push(int x) {
    11         int n = q.size();
    12         q.push(x);
    13         for(int i = 0;i < n ;++i) {
    14             q.push(q.front());
    15             q.pop();
    16         }
    17     }
    18     
    19     /** Removes the element on top of the stack and returns that element. */
    20     int pop() {
    21         int v = q.front();
    22         q.pop();
    23         return v;
    24     }
    25     
    26     /** Get the top element. */
    27     int top() {
    28         return q.front();
    29     }
    30     
    31     /** Returns whether the stack is empty. */
    32     bool empty() {
    33         return q.empty();
    34     }
    35 };
    36 
    37 /**
    38  * Your MyStack object will be instantiated and called as such:
    39  * MyStack* obj = new MyStack();
    40  * obj->push(x);
    41  * int param_2 = obj->pop();
    42  * int param_3 = obj->top();
    43  * bool param_4 = obj->empty();
    44  */
  • 相关阅读:
    命令行中邮件的收发
    关于location对象
    正则表达式
    一家初创公司的 CTO 应当做什么?
    移动数据网络质量的国家奖牌榜
    MFQ&PPDCS测试分析和测试设计框架l学习记录
    Python学习笔记之基本语法学习1
    《用Python做HTTP接口测试》学习感悟
    我的中台的理解
    中台与平台的区别
  • 原文地址:https://www.cnblogs.com/zle1992/p/14825325.html
Copyright © 2011-2022 走看看