当前位置: 代码迷 >> 综合 >> 第一章 栈和队列(由两个栈组成的队列)
  详细解决方案

第一章 栈和队列(由两个栈组成的队列)

热度:11   发布时间:2023-10-11 12:33:12.0

 题目:
         编写一个类,用两个栈实现队列,支持队列的基本操作(add,poll,peek)
 思路:
         1、定义两个栈 pushStack, popStack;
         2、将数据先压入 pushStack,然后将 pushStack 中的数据倒入 popStack,然后从 popStack中取数据,即类似队列的先进先出
         注意:pushStack 中的数据应该一次性倒入 popStack,否则顺序将错误
                  当 popStack 中有数据时不能压入,否则顺序将错误


public class TwoStackQueue {public Stack<Integer> pushStack;public Stack<Integer> popStack;public void pushToPop() {if (popStack.isEmpty()) {while (!pushStack.isEmpty()) {popStack.push(pushStack.pop());}}}public void add(Integer value) {pushStack.push(value);pushToPop();}public Integer poll() {if (popStack.isEmpty() && pushStack.isEmpty()) {throw new NullPointerException("queue is empty");}pushToPop();return popStack.pop();}public void peek() {if (popStack.isEmpty() && pushStack.isEmpty()) {throw new NullPointerException("queue is empty");}pushToPop();popStack.peek();}
}

  相关解决方案