剑指Offer09.用两个栈实现队列

思路1

  • stack1负责所有操作,stack2只是个过客,辅助stack1

代码

//405ms
public class CQueue {
    Stack<Integer> stack1;
    Stack<Integer> stack2;
    public CQueue() {
        this.stack1=new Stack<>();
        this.stack2=new Stack<>();
    }

    public void appendTail(int value) {
        stack1.add(value);
    }

    public int deleteHead() {
        if(stack1.isEmpty()) return -1;
        while(!stack1.isEmpty()&&stack1.size()>1){
            stack2.add(stack1.pop());
        }
        int res=stack1.pop();
        while(!stack2.isEmpty()){
            stack1.add(stack1.pop());
        }
        return res;
    }
}

思路2

  • stack1负责入队列,stack2负责出队列

代码

//66ms
public class CQueue2 {
    //负责入队列
    Stack<Integer> stack1;
    //负责出队列
    Stack<Integer> stack2;

    public CQueue2() {
        this.stack1 = new Stack<>();
        this.stack2 = new Stack<>();
    }

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

    public int deleteHead() {
        if(!stack2.isEmpty()){
            return stack2.pop();
        }else{
            while (!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
            return stack2.isEmpty()?-1:stack2.pop();
        }
    }

}
posted @ 2020-06-30 19:09  YH_Simon  阅读(83)  评论(0编辑  收藏  举报