由两个栈组成的队列
来源:互联网 发布:a站软件 编辑:程序博客网 时间:2024/05/21 14:54
题目:
编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek)。
package com.guet.codetest;
import java.util.Stack;
public 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) {
//int array[]={1,2,3,4,5};
int array[]={1,2};
TwoStacksQueue myQueue=new TwoStacksQueue();
for (int i = 0; i < array.length; i++) {
myQueue.add(array[i]);
}
System.out.println(myQueue.peek());
System.out.println(myQueue.poll());
myQueue.poll();
myQueue.add(4);
//抛出自定义队列空异常
//myQueue.poll();
System.out.println(myQueue.poll());
}
}
import java.util.Stack;
public 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) {
//int array[]={1,2,3,4,5};
int array[]={1,2};
TwoStacksQueue myQueue=new TwoStacksQueue();
for (int i = 0; i < array.length; i++) {
myQueue.add(array[i]);
}
System.out.println(myQueue.peek());
System.out.println(myQueue.poll());
myQueue.poll();
myQueue.add(4);
//抛出自定义队列空异常
//myQueue.poll();
System.out.println(myQueue.poll());
}
}
阅读全文
1 0
- 设计由两个栈组成的队列
- 2.由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成队列
- 栈和队列 由两个栈组成的队列
- 【WG面试算法】由两个栈组成的队列
- 1_2由两个栈组成的队列
- 【栈】由两个栈组成队列
- 1栈和队列--由两个栈组成队列
- 栈和队列---由两个栈组成队列
- 栈和队列(2)--由两个栈组成的队列
- 栈和队列——由两个栈组成的队列
- (一)栈和队列--由两个栈组成的队列 java实现
- 关键字volatile
- 批量添加和批量删除(statement.addBatch() )
- 抓包工具Fiddler的使用
- IBM与麻省理工学院联合建立AI实验室 承诺投资2.4亿美元
- 论QQ浏览器下如何转载CSDN博客
- 由两个栈组成的队列
- 填写企业小程序信息-公司宣传型小程序源代码下载2-视频教程25
- 浅谈UML中的聚合与组合(两者之间的区别)
- 数据库查询优化问题
- vim最实用的配置脚本文件
- 36Kr皇包车-第1个投资退出案例
- VMware安装Ubuntu 15
- ACboy(队列和栈的基础操作)
- VideoCenter App's README