zoukankan      html  css  js  c++  java
  • LeetCode 225. 用队列实现栈

    class MyStack {
        //定义一个队列
        Queue<Integer> queue = new LinkedList<>();
        /** Initialize your data structure here. */
        public MyStack() {
    
        }
        
        /** Push element x onto stack. */
        //队列是先进先出,栈为先进后出,用队列模拟栈时,添加一个元素是在队列的末尾,弹出一个元素是在队头
        //此时把该元素前面的元素全部出队,该元素就到了队首,其余元素再进队,即为一个栈先进后出的顺序
        public void push(int x) {
            queue.add(x);
            int count = queue.size();
            while(count > 1){
                queue.add(queue.remove());
                count--;
            }
        }
        
        /** Removes the element on top of the stack and returns that element. */
        public int pop() {
            return queue.remove();
        }
        
        /** Get the top element. */
        public int top() {
            return queue.peek();
        }
        
        /** Returns whether the stack is empty. */
        public boolean empty() {
            return queue.isEmpty();
        }
    }
    
    /**
     * Your MyStack object will be instantiated and called as such:
     * MyStack obj = new MyStack();
     * obj.push(x);
     * int param_2 = obj.pop();
     * int param_3 = obj.top();
     * boolean param_4 = obj.empty();
     */
  • 相关阅读:
    emacs 集成astyle
    git reflog
    rpm 打包的时候 不进行strip
    gmock
    如何对正在运行的进程,进行heap profile
    linux性能压测工具
    默认宏定义
    gdb fabs错误输出
    基于Clang的缓存型C++编译器Zapcc
    grep 多行 正则匹配
  • 原文地址:https://www.cnblogs.com/peanut-zh/p/13890980.html
Copyright © 2011-2022 走看看