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

package leetcode;

import java.util.Stack;

public class offer_09 {
    //模拟出队列
    private Stack<Integer> s1;
    //模拟进队列
    private Stack<Integer> s2;
    public offer_09() {
        s1=new Stack<Integer>();
        s2=new Stack<Integer>();
    }
    
    public void appendTail(int value) {
        s2.push(value);
    }
    
    public int deleteHead() {
        if(s1.isEmpty()&&s2.isEmpty()) {return -1;}
        //当栈s1不空时,永远都s1中的数据先出栈,也就不需要再把s1中的数据放回到s2中
        if(s1.isEmpty()) {
            while(!s2.isEmpty()) {
                s1.push(s2.pop());
            }
        }
        return s1.pop();
    }

}

 

posted on 2022-03-02 15:42  一仟零一夜丶  阅读(16)  评论(0)    收藏  举报