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  */
  • 相关阅读:
    BZOJ-1625 宝石手镯 01背包(傻逼题)
    BZOJ-2929 洞穴攀岩 最大流Dinic(傻逼题)
    BZOJ3252: 攻略 可并堆
    二逼平衡树 Tyvj 1730 BZOJ3196 Loj#106
    [Noi2016]区间 BZOJ4653 洛谷P1712 Loj#2086
    [NOIP2014]飞扬的小鸟 D1 T3 loj2500 洛谷P1941
    BZOJ4554: [Tjoi2016&Heoi2016]游戏 luoguP2825 loj2057
    BZOJ 2599: [IOI2011]Race 点分治
    POJ1038 Bugs Integrated, Inc 状压DP+优化
    JLOI2015 城池攻占
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8295091.html
Copyright © 2011-2022 走看看