由两个栈组成的队列

2020-09-28  本文已影响0人  Tank_Mao

【题目】
编写一个类,用两个栈实现一个类,支持队列的基本操作(add、poll、peek)。

【要求】
要求即题目。

【解答】
一个栈作为压入栈,记为stackPush,另一个作为弹出栈,记为stackPop。

package pers.mao.stackAndQueue.demo_02;

import java.util.Stack;

/**
 * @author Mao Qingbo
 * @date 2020-09-28
 */
public class TwoStackQueue {
    Stack<Integer> stackPush;
    Stack<Integer> stackPop;

    public TwoStackQueue(){
        this.stackPush = new Stack<Integer>();
        this.stackPop = new Stack<Integer>();
    }

    /**
     * 把stackPush的数据压入stackPop
     */
    private void pushToPop(){
        if(stackPop.empty()){
            while(!stackPush.empty()){
                stackPop.push(stackPush.pop());
            }
        }
    }

    /**
     * newNum进入队列
     * @param newNum 增加数据
     */
    public void add(int newNum){
        stackPush.push(newNum);
        pushToPop();
    }

    /**
     * @return 返回队列的队头
     */
    public int peek(){
        if(stackPush.empty() && stackPop.empty()){
            throw new RuntimeException("This queue is empty!");
        }
        pushToPop();
        return stackPop.peek();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读