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();
        }
    }
    
  • 相关阅读:
    Java 学习资料
    01 html5
    vscode 插件推荐
    08 css高级
    07 css定位
    06 css布局浮动
    05 css盒子
    04 css复合选择器 标签 行高
    03 css字体样式
    02 css基础选择器
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/8353353.html
Copyright © 2011-2022 走看看