zoukankan      html  css  js  c++  java
  • 232. Implement Queue using Stacks

    原题链接:https://leetcode.com/problems/implement-queue-using-stacks/description/
    实现如下:

    import java.util.Stack;
    
    /**
     * Created by clearbug on 2018/4/5.
     *
     * 这只是最普通最简单的一种方法实现,官方答案里面的第二种方法真不错,整体上提高了时间效率!
     */
    public class MyQueue {
    
        private Stack<Integer> stack1;
    
        private Stack<Integer> stack2;
    
        /** Initialize your data structure here. */
        public MyQueue() {
            stack1 = new Stack<>();
            stack2 = new Stack<>();
        }
    
        /** Push element x to the back of queue. */
        public void push(int x) {
            while (!stack1.empty()) {
                stack2.push(stack1.pop());
            }
            stack2.push(x);
            while (!stack2.empty()) {
                stack1.push(stack2.pop());
            }
        }
    
        /** Removes the element from in front of queue and returns that element. */
        public int pop() {
            return stack1.pop();
        }
    
        /** Get the front element. */
        public int peek() {
            return stack1.peek();
        }
    
        /** Returns whether the queue is empty. */
        public boolean empty() {
            return stack1.empty();
        }
    
    }
    
  • 相关阅读:
    将个人博客与github关联
    docker镜像制作
    perf命令
    vmstat命令
    ps命令
    top命令
    linux查看当前用户登陆信息
    .NET CORE应用程序启动
    WebAPI简介
    Redis-位图
  • 原文地址:https://www.cnblogs.com/optor/p/8727014.html
Copyright © 2011-2022 走看看