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

2020-08-09  本文已影响0人  bangbang2
image.png
image.png

stack2作为辅助栈,负责pop操作
1:队列的push操作正常即可
2:在pop的时候,如果s2.isEmpty()&&!s1.isEmpty(),就将stack1里的元素全部放在stack2中,如果s2.isEmpty()&&s1.isEmpty(),都为空,直接返回-1

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

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

猜你喜欢

热点阅读