leetcode 刷题-剑指offer-09题

leetcode 刷题-剑指offer-09题

题目

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTaildeleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

示例 1:

输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]

示例 2:

输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]

解答

新手上路,才学疏浅,望斧正

class CQueue {
    Stack<Integer> stack1,stack2;
    int XNumber;

    public CQueue() {
        stack1=new Stack<Integer>();
        stack2=new Stack<Integer>();
        XNumber =0;
    }

    public void appendTail(int value) {
        stack1.push(value);
        XNumber++;
    }

    public int deleteHead() {
        int value=-1;

        if(XNumber==0){
            return -1;
        }
        if(!stack2.isEmpty()){
            value=stack2.pop();
            XNumber--;
            return value;
        }else {
            while (!stack1.isEmpty())
                stack2.push(stack1.pop());
            value=stack2.pop();
            XNumber--;
            return value;
        }
    }
}
上一篇:剑指 Offer 09. 用两个栈实现队列


下一篇:Dubbo常用功能09--参数回调