美文网首页
10-用栈实现队列

10-用栈实现队列

作者: weyan | 来源:发表于2021-08-14 22:17 被阅读0次

    代码:
    package 栈;
    
    import java.util.Stack;
    
    /**_232_用栈实现队列
     * url: https://leetcode-cn.com/problems/implement-queue-using-stacks/
     **/
    public class _232_用栈实现队列 {
        private Stack<Integer> inStack;
        private Stack<Integer> outStack;
        /** Initialize your data structure here. */
        public _232_用栈实现队列() {
            inStack = new Stack<>();
            outStack = new Stack<>();
        }
        
        /** Push element x to the back of queue. 入队*/
        public void push(int x) {
            inStack.push(x);
        }
        
        /** Removes the element from in front of queue and returns that element.出队 */
        public int pop() {
            checkOutStack();
            return outStack.pop();
        }
        
        /** Get the front element.队头 */
        public int peek() {
            checkOutStack();
            //返回栈顶元素
            return outStack.peek();
        }
        
        /** Returns whether the queue is empty.是否为空 */
        public boolean empty() {
            return inStack.isEmpty() && outStack.isEmpty();
        }
        
        private void checkOutStack() {
            if (outStack.isEmpty()) {
                while (!inStack.isEmpty()) {
                    outStack.push(inStack.pop());
                }
            }
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:10-用栈实现队列

          本文链接:https://www.haomeiwen.com/subject/xuowjltx.html