2.由两个栈组成的队列
2015-10-03 18:16
218 查看
题目:用两个栈实现队列,能够支持级别的操作(add poll peek)
思路:用一个栈存数据,另一个负责取数据,当取数据的栈空的时候,就把存数据的那个栈的数据全部取过来就行了,当两个栈都为空,则队列为空
import java.util.Stack;
public class StackToQueue {
public Stack<Integer> inStack = new Stack<Integer>();
public Stack<Integer> outStack = new Stack<Integer>();
public void add(int e){
inStack.push(e);
}
public int poll(){
if(inStack.isEmpty()&&outStack.isEmpty())
throw new RuntimeException("stack is empty ");
else if(outStack.isEmpty()){
while(!inStack.isEmpty()){
outStack.push(inStack.pop());
}
}
return outStack.pop();
}
public int peek(){
if(inStack.isEmpty()&&outStack.isEmpty())
throw new RuntimeException("stack is empty ");
else if(outStack.isEmpty()){
while(!inStack.isEmpty()){
outStack.push(inStack.pop());
}
}
return outStack.peek();
}
}
思路:用一个栈存数据,另一个负责取数据,当取数据的栈空的时候,就把存数据的那个栈的数据全部取过来就行了,当两个栈都为空,则队列为空
import java.util.Stack;
public class StackToQueue {
public Stack<Integer> inStack = new Stack<Integer>();
public Stack<Integer> outStack = new Stack<Integer>();
public void add(int e){
inStack.push(e);
}
public int poll(){
if(inStack.isEmpty()&&outStack.isEmpty())
throw new RuntimeException("stack is empty ");
else if(outStack.isEmpty()){
while(!inStack.isEmpty()){
outStack.push(inStack.pop());
}
}
return outStack.pop();
}
public int peek(){
if(inStack.isEmpty()&&outStack.isEmpty())
throw new RuntimeException("stack is empty ");
else if(outStack.isEmpty()){
while(!inStack.isEmpty()){
outStack.push(inStack.pop());
}
}
return outStack.peek();
}
}
相关文章推荐
- Machine Learning Basics(要点)
- 常见系统服务及进程
- ISO/IEC 9899:2011 条款6.5.7——按位移位操作符
- POJ 2886 线段树单点更新
- java线程详解(一)
- 【Python】二分查找算法
- 我的常用脚本记录
- 实现android文字描边功能
- 第二章 python中重要的数据结构(下)
- Android源码之Gallery专题研究(1)
- Linux Shell学习笔记5:理解Linux文件权限
- HTTP 基础知识
- 第二个论文修改手记
- pat1020Tree Traversals (25)
- 我的vim配置
- 亿级 Web 系统搭建:单机到分布式集群
- Linux网络协议栈(一)——Socket入门(1)
- Bash基础
- VIM之模式
- 返回值作为标志