剑指Offer------用两个栈实现队列(用两个队列实现栈)
来源:互联网 发布:禁毒网络知识登录竞赛 编辑:程序博客网 时间:2024/06/05 10:37
问题一:用两个栈实现一个队列的功能?要求给出算法和思路
<分析>:
入队:将元素进栈A
出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B,栈B出栈;
如果不为空,栈B直接出栈。
import java.util.Stack;/** * * @author zy * @date 2017年10月2日 下午2:02:23 * @Decription 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。 */public class StackToQueue {Stack<Integer> stack1 = new Stack<Integer>();Stack<Integer> stack2 = new Stack<Integer>();public void push(int node) {stack1.push(node);}public int pop() {int a;if (stack2.empty()) {while(!stack1.empty()){a = stack1.pop();stack2.push(a);}}a = stack2.pop();return a;}}
问题二:用两个队列实现一个栈的功能?要求给出算法和思路
<分析>
入队:将元素进队列A
出队:判断队列A中元素是否为1,如果等于1,则出队列,否则将队列A中的元素,依次出队列并放入队列B,直到队列A中的元素留下一个,然后队列A出队列,再把队列B中的元素出队列依次放入队列A中。
阅读全文
0 0
- [剑指offer]用两个栈实现队列
- 【剑指offer】用两个栈实现队列
- 剑指offer--用两个栈实现队列
- 剑指Offer-用两个栈实现队列
- 剑指offer:用两个栈实现队列
- 《剑指offer》用两个栈实现队列
- 用两个栈实现队列(剑指offer)
- 剑指 offer:用两个栈实现队列
- 【剑指Offer】用两个栈实现队列
- 剑指offer-用两个栈实现队列
- 《剑指offer》-用两个栈实现队列
- 剑指offer 用两个栈实现队列
- 剑指offer 用两个栈实现队列
- [剑指offer]用两个栈实现队列
- 剑指offer--用两个栈实现队列
- 剑指offer|用两个栈实现队列
- 【剑指offer】用两个栈实现队列
- 剑指offer----用两个栈实现队列
- stm32 非DMA方式 多路ADC ADC1,ADC3两种方式求助
- 无法启动此程序,因为计算机丢失opencv_core249d.dll
- randomwalking(10.2hu测)
- 设计模式的分类
- 关于对象初探
- 剑指Offer------用两个栈实现队列(用两个队列实现栈)
- 344. Reverse String(第四周)
- org.apache.axis2.databinding.ADBException: Unexpected subelement arg0 的解决方法
- JavaScript基础案例实现
- windows下图片标识工具labelimg的安装与使用
- SpringMVC统一异常处理
- 适配器(Adapter)模式
- 进程IPC---流式套接字
- java访问数据库