栈和队列 由两个栈组成的队列
来源:互联网 发布:雷蛇键盘 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();}}
阅读全文
0 0
- 栈和队列 由两个栈组成的队列
- 由两个栈组成队列
- 设计由两个栈组成的队列
- 2.由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 1栈和队列--由两个栈组成队列
- 栈和队列---由两个栈组成队列
- 栈和队列(2)--由两个栈组成的队列
- 栈和队列——由两个栈组成的队列
- (一)栈和队列--由两个栈组成的队列 java实现
- 【栈】由两个栈组成队列
- 【WG面试算法】由两个栈组成的队列
- 1_2由两个栈组成的队列
- Android设计模式之(20)----装饰器模式
- MYSQL-实现split函数
- 剑指Offer_面试题36_数组中的逆序对
- &指针+1浅析
- 工作流
- 栈和队列 由两个栈组成的队列
- mysql tinyint类型返回如何返回数值
- Android性能优化之巧用软引用与弱引用优化内存使用
- svn 项目转移到 git 码云
- 基于TCP协议的简易C/S通信
- 插值与拟合
- 编译、运行脚本和Command Line命令行参数设置
- Android系统架构
- Java并发包中常用类