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  */
  • 相关阅读:
    iTerm2分屏快捷键
    k8s中运维/测试常用的命令整理(随时更新)
    httpRunner自动化测试用例使用笔记
    Git学习笔记-快速上手(mac系统)
    RBAC权限控制逻辑笔记
    CPS中有关CICD的配置
    LDAP中filter的使用
    Docker初级入门
    C语言 实现 HashTable
    从三个线程 排队打印 , 到 多个线程打印
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8295091.html
Copyright © 2011-2022 走看看