java两栈实现一个队列

思路

入队时,将元素压入s1。出队时,判断s2是否为空,如不为空,则直接弹出顶元素;如为空,则将s1的元素逐个“倒入”s2,把最后一个元素弹出并出队。

public class QueneWithTwoStacks {
    
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    
    public QueneWithTwoStacks() {
        stack1 = new Stack<Integer>();
        stack2 = new Stack<Integer>();
    }
    
    public Integer poll() {
        if (stack1.isEmpty() && stack2.isEmpty())
            return null;
        
        Integer re = null;
        if (!stack2.isEmpty()) {
            re = stack2.pop();
        } else {
            while (!stack1.isEmpty()) {
                re = stack1.pop();
                stack2.push(re);
            }
            poll();
        }
        return re;
    }
    
    public Integer insert(int o) {
        stack1.push(o);
        return o;
    }
    
    public static void main(String[] args) {
        QueneWithTwoStacks qw = new QueneWithTwoStacks();
        qw.insert(2);
        qw.insert(1);
        qw.insert(3);
        qw.insert(4);
        System.out.println("出栈----" + qw.poll());
        qw.insert(5);
        qw.insert(9);
        System.out.println("出栈----" + qw.poll());
        System.out.println("出栈----" + qw.poll());
    }
}
原文地址:https://www.cnblogs.com/amos-s/p/6536370.html