栈和队列 由两个栈组成的队列

来源:互联网 发布:雷蛇键盘 mac 编辑:程序博客网 时间:2024/05/17 23:27

【题目】

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

【解答】

栈的特点是先进后出,而队列的特点是先进先出。我们用两个栈正好能把顺序反过来,实现类似队列的操作。

【注意事项】

1.如果stackPush 要往stackPop中压入数据,那么必须一次性把stackPush中的数据全部压入。

2.如果stackPop不为空,stackPush绝不能向stackPop中压入数据。

import java.util.Stack;//由两个栈组成的队列public class TwoStackQueue {private Stack<Integer> stackPush;private Stack<Integer> stackPop;public TwoStackQueue(){this.stackPop = new Stack<Integer>();this.stackPush = new Stack<Integer>();}public void add(int pushInt){stackPush.push(pushInt);}public int poll(){if(stackPush.isEmpty() && stackPop.isEmpty())throw new RuntimeException("the queue is empty");else if(stackPop.isEmpty()){while(!stackPush.empty()){stackPop.push(stackPush.pop());}}return stackPop.pop();}public int peek(){if(stackPop.isEmpty() && stackPush.isEmpty())throw new RuntimeException("the queque is empty");else if(stackPop.isEmpty()){while(!stackPush.isEmpty())stackPop.push(stackPush.pop());}return stackPop.peek();}}


原创粉丝点击