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

    Implement the following operations of a stack using queues.

    • push(x) -- Push element x onto stack.
    • pop() -- Removes the element on top of the stack.
    • top() -- Get the top element.
    • empty() -- Return whether the stack is empty.

    Notes:

      • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
      • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
      • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

    用队列实现栈的功能

    C++(2ms):

     1 class MyStack {
     2 public:
     3     queue<int> q ;
     4     /** Initialize your data structure here. */
     5     MyStack() {
     6         
     7     }
     8     
     9     /** Push element x onto stack. */
    10     void push(int x) {
    11         q.push(x) ;
    12         for(int i = 0 ; i < q.size()-1 ; i++){
    13             q.push(q.front()) ;
    14             q.pop() ;
    15         }
    16     }
    17     
    18     /** Removes the element on top of the stack and returns that element. */
    19     int pop() {
    20         int t = q.front() ;
    21         q.pop() ;
    22         return t ;
    23     }
    24     
    25     /** Get the top element. */
    26     int top() {
    27         return q.front() ;
    28     }
    29     
    30     /** Returns whether the stack is empty. */
    31     bool empty() {
    32         return q.empty() ;
    33     }
    34 };
    35 
    36 /**
    37  * Your MyStack object will be instantiated and called as such:
    38  * MyStack obj = new MyStack();
    39  * obj.push(x);
    40  * int param_2 = obj.pop();
    41  * int param_3 = obj.top();
    42  * bool param_4 = obj.empty();
    43  */
  • 相关阅读:
    php魔术方法
    适用所有手机号码的正则表达式
    js按回车事件提交
    php 顺序线性表
    PLSQL连接远程oracle配置
    Jmeter 接口测试 —— 3种参数化方式
    Jmeter 接口测试 —— 3种采样器的使用
    【LICEcap】怎样用LICEcap录制屏幕及GIF图片
    WPS标题自动编号
    UT、IT、ST、UAT
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8295091.html
Copyright © 2011-2022 走看看