剑指 Offer 09. 用两个栈实现队列

题目:https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/

解题思路参考 这篇题解

代码运行结果:

执行用时:55 ms, 在所有 Java 提交中击败了82.94%的用户

内存消耗:47.7 MB, 在所有 Java 提交中击败了100.00%的用户

class CQueue {

    //s1作为队列的尾部,用于添加元素
    private Stack s1;

    //s2作为队列的头部,用于删除元素
    private Stack s2;

    public CQueue() {
        s1 = new Stack<>();
        s2 = new Stack<>();
    }
    
    public void appendTail(int value) {
        s1.push(value);
    }
    
    public int deleteHead() {
        if(!s2.isEmpty())
            return s2.pop();
        while(!s1.isEmpty())
            s2.push(s1.pop());
        return s2.isEmpty() ? -1 : s2.pop();
    }
}

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue obj = new CQueue();
 * obj.appendTail(value);
 * int param_2 = obj.deleteHead();
 */

 

你可能感兴趣的:(LeetCode)