2020-04-09(232. 用栈实现队列*)

难度 简单
和昨天的队列实现栈类似,昨天用队列实现栈的时候没有在入栈的时候处理而是在出栈时候处理,很麻烦。今天吸取教训在push的时候进行处理。

/** Initialize your data structure here. */
    Stack<Integer> mStack = new Stack<Integer>();
    public MyQueue() {
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        Stack<Integer> tempS = new Stack<Integer>();
        while(!mStack.isEmpty()){
            tempS.push(mStack.pop());
        }
        mStack.push(x);
        while(!tempS.isEmpty()){
            mStack.push(tempS.pop());
        }
        tempS = null;        
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        return mStack.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        return mStack.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return mStack.isEmpty();
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容