美文网首页笔试&&面试经验程序员面试的那些小事
编写一个类,用两个栈实现队列,支持队列的基本操作(add、pol

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

作者: 624c95384278 | 来源:发表于2017-11-28 17:00 被阅读41次

本题来自程序员代码面试指南


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

实现思路

一个栈作为压入栈,在压入数据时只往这个栈中压入,记为stackPush;
另一个栈只作为弹出栈,在弹出数据时只从这个栈弹出,记为stackPop。
实现这个有俩个关键点

  • 1.如果stackPush要往stackPop中压入数据,那么必须一次性把stackPush中的数据全部压入。
  • 2.如果stackPop不为空,stackPush绝对不能向stackPop中压入数据。
    java Stack类中的isEmpty()和empty()的区别
public class TwoStacksQueue {
    private Stack<Integer> stackPush;//压入数据栈
    private Stack<Integer> stackPop; //弹出数据栈

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

    /**
     * 入队操作
     * 直接将数据压入压入数据栈
     * @param push
     */
    public void push(int push) {
        this.stackPush.push(push);
    }


    /**
     * 出队操作
     * @return
     */
    public int poll() throws Exception {
        if (stackPush.isEmpty() && stackPop.isEmpty()) {
            throw new Exception("队列中没有数据");
        } else if (stackPop.isEmpty()) {
            //弹出数据栈为空,可以将整个压入数据栈中的数据倒入弹出数据栈
            while (!stackPush.isEmpty()) {
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.pop();
    }

    /**
     * 返回队头元素
     * @return
     * @throws Exception
     */
    public int peek() throws Exception {
        if (stackPush.isEmpty() && stackPop.isEmpty()) {
            throw new Exception("队列中没有数据");
        }else if (stackPop.isEmpty()) {
            //弹出数据栈为空,可以将整个压入数据栈中的数据倒入弹出数据栈
            while (!stackPush.isEmpty()) {
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.peek();
    }
}

附上github地址

相关文章

  • 【算法题】由两个栈组成的队列

    编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek)。 解题思路 为了实现栈后进先出的特...

  • 由两个栈组成的队列

    题目描述 编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek) 问题解答 要实现队列的先...

  • 由两个栈组成的队列

    题目 编写一个类,用两个栈实现队列,支持队列的基本操作(add, poll, peek) 要求 无 思路 使用两个...

  • 两个栈实现一个队列

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

  • 编写一个类,用两个栈实现队列,支持队列的基本操作(add、pol

    本题来自程序员代码面试指南 编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek) 实现思...

  • 由两个栈组成的队列

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

  • 4_4双栈队列

    编写一个类,只能用两个栈结构实现队列,支持队列的基本操作(push,pop)。 给定一个操作序列ope及它的长度n...

  • 双栈模拟队列

    编写一个类,只能用两个栈结构实现队列,支持队列的基本操作(push,pop)。其实动手写一下,也很容易知道这个过程...

  • 剑指 offer:5、用两个栈实现队列

    5. 用两个栈实现队列 题目描述 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类...

  • 剑指Offer(五)

    剑指Offer(五) 用两个栈实现队列 题目描述: 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列...

网友评论

    本文标题:编写一个类,用两个栈实现队列,支持队列的基本操作(add、pol

    本文链接:https://www.haomeiwen.com/subject/frsebxtx.html