Implement Queue by Two Stacks 解题报告
来源:互联网 发布:电子书设计软件 编辑:程序博客网 时间:2024/05/17 20:33
Implement Queue by Two Stacks
Description
As the title described, you should only use two stacks to implement a queue’s actions.
The queue should support push(element)
, pop()
and top()
where pop is pop the first(a.k.a front) element in the queue.
Both pop and top methods should return the value of first element.
Example
push(1)pop() // return 1push(2)push(3)top() // return 2pop() // return 2
实现思路
- 设有两个栈A和栈B,每次添加新元素时,都放入栈A中,每次需要从数据结构中取元素,都从栈B中取。
- 一旦栈中没有可取元素了,就将A中所有元素压入栈B中,假设元素压入栈A顺序是:
1,2,3,4,5
,从左到右对应先后次序,如果从栈A中取出,则是5,4,3,2,1
(即先取5,最后取1),然后再放入栈B中,则在栈B中的元素顺序为5,4,3,2,1
,再从栈B取出元素,则后进先出,即依次取出1,2,3,4,5
,从而总体形成了一个(1)先进(1)先出的队列顺序。
public class MyQueue { private Stack<Integer> stack1; private Stack<Integer> stack2; private Stack<Integer> curStack; public MyQueue() { stack1 = new Stack<>(); stack2 = new Stack<>(); } public void push(int element) { stack1.push(element); } public int pop() { if(stack2.empty()){ while(!stack1.empty()){ stack2.push(stack1.pop()); } } return stack2.pop(); } public int top() { if(stack2.empty()){ while(!stack1.empty()){ stack2.push(stack1.pop()); } } return stack2.peek(); }}
0 0
- Implement Queue by Two Stacks 解题报告
- implement-queue-by-two-stacks
- Implement Queue by Two Stacks
- Implement Queue by Two Stacks
- Implement Queue by Two Stacks
- Implement Queue by Two Stacks
- implement a queue by using two stacks
- [刷题]Implement Queue by Two Stacks
- lintcode: Implement Queue by Two Stacks
- #40 Implement Queue by Two Stacks
- [Lintcode]Implement Queue by Two Stacks
- Lintcode 40:Implement Queue by Two Stacks
- LeetCode-Implement Queue using Stacks-解题报告
- 【LeetCode】Implement Queue using Stacks 解题报告
- implement a queue by using two stacks [No. 31]
- Lintcode40 Implement Queue by Two Stacks solution 题解
- 【LeetCode】 Implement Queue by Two Stacks用栈实现队列
- leetcode解题报告232——Implement Queue using Stacks
- Matconvnet实现目标检测(person&car)
- Struts2存取数据
- Virtualbox中Linux添加新磁盘并创建分区
- 随机数和随机字符串的生成
- MySQL数据恢复的九把瑞士军刀
- Implement Queue by Two Stacks 解题报告
- ubuntu 工具 安装笔记
- 在微信网页中,实现微信通过菜单‘在浏览器中打开’跳转到指定的url
- repo 获取各个库的tag代码
- android JMessage集成
- linux中ldconfig命令 以及 添加动态库自动搜索路径
- Linux管线命令之排序命令(sort, wc, uniq)
- 轮廓的查找、表达、绘制、特性及匹配(How to Use Contour? Find, Component, Construct, Features & Match)
- 【Unity3D】对话