zoukankan      html  css  js  c++  java
  • 使用一个队列完成一个栈

    2018-01-25 21:11:02

    题目描述:

    问题求解:

    队列的特点是先进先出,栈的特点是先进后出。如果在push的时候,对队列中的元素进行reverse,那么就可以很容易的进行pop(),top(),empty()等操作。

    class MyStack {
        Queue<Integer> queue;
    
        /** Initialize your data structure here. */
        public MyStack() {
            queue = new LinkedList<>();
        }
        
        /** Push element x onto stack. */
        public void push(int x) {
            int size = queue.size();
            queue.offer(x);
            while (size-- > 0) {
                queue.offer(queue.poll());
            }
            
        }
        
        /** Removes the element on top of the stack and returns that element. */
        public int pop() {
            return queue.poll();
        }
        
        /** Get the top element. */
        public int top() {
            return queue.peek();
        }
        
        /** Returns whether the stack is empty. */
        public boolean empty() {
            return queue.isEmpty();
        }
    }
    
  • 相关阅读:
    oracle使用expdp备份数据库
    用Setuptools构建和分发程序包
    C#5.0-原生异步编程方式
    任务并行库
    线程-线程池1
    多线程-3(同步)
    多线程-2(线程同步)
    线程---1
    高性能-GC3
    高性能-GC2
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/8353353.html
Copyright © 2011-2022 走看看