由两个栈组成的队列
来源:互联网 发布:最小公倍数求法 c语言 编辑:程序博客网 时间:2024/04/30 11:13
题目:用两个栈实现队列,能够支持级别的操作(add poll peek)
package zcy_1;import java.util.Stack;public class Problem_02_TwoStacksImplementQueue {public static class TwoStacksQueue {public Stack<Integer> stackPush;public Stack<Integer> stackPop;public TwoStacksQueue() {stackPush = new Stack<Integer>();stackPop = new Stack<Integer>();}public void add(int pushInt) {stackPush.push(pushInt);}public int poll() {if (stackPop.empty() && stackPush.empty()) {throw new RuntimeException("Queue is empty!");} else if (stackPop.empty()) {while (!stackPush.empty()) {stackPop.push(stackPush.pop());}}return stackPop.pop();}public int peek() {if (stackPop.empty() && stackPush.empty()) {throw new RuntimeException("Queue is empty!");} else if (stackPop.empty()) {while (!stackPush.empty()) {stackPop.push(stackPush.pop());}}return stackPop.peek();}}public static void main(String[] args) {TwoStacksQueue test = new TwoStacksQueue();test.add(1);test.add(2);test.add(3);System.out.println(test.peek());System.out.println(test.poll());System.out.println(test.peek());System.out.println(test.poll());System.out.println(test.peek());System.out.println(test.poll());}}
0 0
- 设计由两个栈组成的队列
- 2.由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成队列
- 栈和队列 由两个栈组成的队列
- 【WG面试算法】由两个栈组成的队列
- 1_2由两个栈组成的队列
- 【栈】由两个栈组成队列
- 1栈和队列--由两个栈组成队列
- 栈和队列---由两个栈组成队列
- 栈和队列(2)--由两个栈组成的队列
- 栈和队列——由两个栈组成的队列
- (一)栈和队列--由两个栈组成的队列 java实现
- android 开发环境 简介
- 2016 百度之星 ProblemA -- (Hash+乘法逆元,利用两种方法求逆元)
- 使用AFNetworking
- C++:STL标准入门汇总
- 面试题24
- 由两个栈组成的队列
- Qt 环境下使用Gsl( GNU Scientific Library)库
- SSO单点登录
- 使用ubuntu忘记root密码该如何重置
- Android多点触摸交互处理
- Javascript中的shift() 和 pop()比较
- 大端小端存储的含义及判断
- hdu_3182_Hamburger Magi(状压DP)
- nodejs模仿优酷网站,有后端