双栈实现队列

俩个栈实现队列的功能,头部删除,尾部添加,是否为空,返回队头

/**
 * 用俩个栈实现队列
 */
public class MyQueue {

    Stack<Integer> stack1,stack2;

    public MyQueue() {
        this.stack1 = new Stack<>();//主栈
        this.stack2 = new Stack<>();//辅助栈
    }
    /** 添加元素到队尾 */
    public void add(int x){
        stack1.push(x);

    }

    /** 删除队头的元素并返回 */
    public int deleteHead(){
        // 先调用 peek 保证 s2 非空
        getHead();
        return stack2.pop();
    }

    /** 返回队头元素 */
    public int getHead(){
        //如果s2不为空,返回s2栈顶元素。如果为空将s1的元素都加入s1中,返回s2栈顶元素
        if(stack2.isEmpty()){
            while (!stack1.isEmpty())
                stack2.push(stack1.pop());
        }
        return stack2.peek();
    }

    /** 判断队列是否为空 */
    public boolean empty(){
        return stack1.isEmpty()&&stack2.isEmpty();
    }

    public static void main(String[] args) {
        MyQueue myQueue=new MyQueue();
        myQueue.add(1);
        myQueue.add(2);
        myQueue.add(3);
        myQueue.add(4);
        System.out.println(myQueue.getHead());
        myQueue.deleteHead();
        System.out.println(myQueue.getHead());

    }
}
posted @ 2020-04-22 15:31  程序员小宇  阅读(312)  评论(0编辑  收藏  举报