TreeviewCopyright © aleen42 all right reserved, powered by aleen42

232. 用栈实现队列

https://leetcode-cn.com/problems/implement-queue-using-stacks/

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-07-16 18:47:49
 * @Description: https://leetcode-cn.com/problems/implement-queue-using-stacks/
 * @FilePath: \leetcode-googtech\#232. Implement Queue using Stacks\Solution.java
 */ 
class MyQueue {

    /** Define the stack. */
    private Stack<Integer> inputStack;
    private Stack<Integer> outputStack;

    /** Initialize your data structure here. */
    public MyQueue() {
        inputStack = new Stack<>();
        outputStack = new Stack<>();
    }

    /** Push element x to the back of queue. */
    public void push(int x) {
        inputStack.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        copyElement();
        return outputStack.pop();
    }

    /** Get the front element. */
    public int peek() {
        copyElement();
        return outputStack.peek();
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return inputStack.isEmpty() && outputStack.isEmpty();
    }

    /** Copy the elements from inputStack to outputStack. */
    public void copyElement(){
        if(outputStack.isEmpty()){
            while(!inputStack.isEmpty()){
                outputStack.push(inputStack.pop());
            }
        }
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

Python

# updating
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""