第二题:如何使用栈实现队列(使用两个栈实现队列)

版权声明:Please make the source marked https://blog.csdn.net/qq_31807385/article/details/86018552

题目要求:

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

 代码实现与分析:

package com.isea.brush;

import java.util.Stack;

/**
 * 编写一个类,用两个栈实现队列,支持队列的基本操作(add,poll,peek)
 * 实现思路:一个stackData栈用来入栈,一个stackHelp用来出栈,每一次入栈,直接将数据存放进入dataStack即可
 * 每一个出栈,判断stackHelp栈是否为空,如果是空,将stackData栈中的内容倾倒到stackHelp栈中,然后再出栈,否者直接出栈
 * 这里发生的倾倒操作必须要stackHelp栈为空。
 */
public class TwoStackQueue {
    private Stack<Integer> stackData;
    private Stack<Integer> stackHelp;

    public TwoStackQueue() {
        stackData = new Stack<Integer>();
        stackHelp = new Stack<Integer>();
    }

    /**
     * 入队操作
     *
     * @param num
     */
    public void add(int num) {
        stackData.push(num);
    }

    /**
     * 出队操作
     *
     * @return
     */
    public int poll() {
        if (stackData.isEmpty() && stackHelp.isEmpty()) {
            throw new IllegalArgumentException("The queue is empty...");
        }
        dump();
        return stackHelp.pop();
    }

    /**
     * 将stackData中的数据倾倒入stackHelp中
     */
    private void dump() {
        if (stackHelp.isEmpty()) {
            while (!stackData.isEmpty()) {
                stackHelp.add(stackData.pop());
            }
        }
    }

    /**
     * 查看队首的元素
     *
     * @return
     */
    public int peek() {
        if (stackHelp.isEmpty() && stackData.isEmpty()){
            throw new IllegalArgumentException("The queue is empty...");
        }
        dump();
        return stackHelp.peek();
    }
    
}

猜你喜欢

转载自blog.csdn.net/qq_31807385/article/details/86018552
今日推荐