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.

    Example:

    MyStack stack = new MyStack();
    
    stack.push(1);
    stack.push(2);  
    stack.top();   // returns 2
    stack.pop();   // returns 2
    stack.empty(); // returns false

    Notes:

    • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is emptyoperations 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).
        class MyStack {
          Queue<Integer> q = new LinkedList<Integer>();
          
          // Push element x onto stack.
          public void push(int x) {
              q.add(x);
              
              int n = q.size();
              while (n-- > 1)
                  q.add(q.poll());
          }
      
          // Removes the element on top of the stack.
          public int pop() {
              return q.poll();
          }
      
          // Get the top element.
          public int top() {
              return q.peek();
          }
      
          // Return whether the stack is empty.
          public boolean empty() {
              return q.isEmpty();
          }
      
        }

      用一个queue即可,遇到要push的,先push到队尾,然后一边poll一边offer相当于除队尾外reverse。

    • Queue的remove(), poll()都是取出第一个element,用poll()更好因为如果为空可以返回null
    • Queue的offer(),add()都是加入新元素,用offer更有效率
    • Queue的peek(),element()都是查询第一个element,用peek更好因为如果为空可以返回null

    另,stack有empty()和isEmpty()方法,源代码显示其实是一致的,只是后续引入了isEmpty()保留了empty方法

  • 相关阅读:
    1155 Heap Paths (30 分)
    1147 Heaps (30 分)
    1098 Insertion or Heap Sort (25 分)
    12.SpringMVC 获得 请求头信息
    11.SpringMVC 获得Servlet相关API
    10.SpringMVC 自定义类型转换器
    18. VUE 数组的响应式
    017 vue 关于 v-for 指令内部算法
    17. VUE v-show 和 v-if 的区别
    16. VUE 的 小案列
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11415978.html
Copyright © 2011-2022 走看看