剑指 Offer 09. 用两个栈实现队列 +java中栈和队列的使用

题目来源

题目链接

题目详情

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 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]

提示:

  • 1 <= values <= 10000
  • 最多会对 appendTail、deleteHead 进行 10000 次调用

题解分析

解法一:输入栈+输出栈

class CQueue {
    private Deque<Integer> stain;
    private Deque<Integer> staout;
    public CQueue() {
        stain = new LinkedList<>();
        staout = new LinkedList<>();
    }
    
    public void appendTail(int value) {
        stain.offerFirst(value);
    }
    
    public int deleteHead() {
        if(staout.isEmpty()){
            while(!stain.isEmpty()){
                staout.offerFirst(stain.pollFirst());
            }
        }
        if(staout.isEmpty()){
            return -1;
        }else{
            return staout.pollFirst();
        }
    }
}

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

解法二:临时栈

class CQueue {

   private Stack<Integer> sta1;
    private Stack<Integer> sta2;
    public CQueue() {
        sta1 = new Stack<>();
        sta2 = new Stack<>();
    }

    public void appendTail(int value) {
        while(!sta1.empty()){
            sta2.push(sta1.pop());
        }
        sta1.push(value);
        while(!sta2.empty()){
            sta1.push(sta2.pop());
        }
    }

    public int deleteHead() {
        if(sta1.empty())
            return -1;
        else return sta1.pop();
    }
}

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue obj = new CQueue();
 * obj.appendTail(value);
 * int param_2 = obj.deleteHead();
 */
posted @ 2020-12-09 08:56  Garrett_Wale  阅读(61)  评论(0编辑  收藏  举报