用两个栈实现一个队列
2015-10-22 08:27
363 查看
1.入队列时,将元素放入栈s1
2.出队列时,如果栈s2不为空,则直接将s2栈顶元素出栈;如果s2为空,则将s1所有元素出栈并放入s2,最后将s2栈顶元素出栈
输出:
队列首元素:1
队列首元素:2
2.出队列时,如果栈s2不为空,则直接将s2栈顶元素出栈;如果s2为空,则将s1所有元素出栈并放入s2,最后将s2栈顶元素出栈
package me.wcy.j2se.datastructure; import java.util.Stack; /** * 两个栈实现一个队列 * * @author chenyan.wang * * @param <E> */ public class MyQueue<E> { public static void main(String[] args) { MyQueue<Integer> queue = new MyQueue<>(); queue.add(1); queue.add(2); System.out.println("队列首元素:" + queue.poll()); System.out.println("队列首元素:" + queue.poll()); } private Stack<E> s1; private Stack<E> s2; public MyQueue() { s1 = new Stack<>(); s2 = new Stack<>(); } public void add(E e) { s1.push(e); } public E poll() { if (s2.size() == 0) { while (!s1.isEmpty()) { s2.push(s1.pop()); } } return s2.pop(); } public boolean isEmpty() { return s1.isEmpty() && s2.isEmpty(); } }
输出:
队列首元素:1
队列首元素:2
相关文章推荐
- C/C++面试题:class和struct有什么区别?
- Zigzag Iterator 解答
- Windows 下环境变量设置(命令行)
- eclipse jsp html 格式化 format
- **LeetCode-Inorder Successor in BST
- iOS面试整理
- 【状压bfs】ctsc 1999 补丁vs错误
- sdwebimage如何获取缓存大小以及清除缓存
- HA集群之二:部署HA wordpress Cluster
- 微服务年度总结,看完这个你应该知道如何回答别人的问题了。
- mysql 不能插入中文和显示中文
- 矩阵算法 高斯消元 行列式 矩阵的秩
- 关于ExecuteNonQuery()执行成功却返回-1的问题
- 按位与运算符
- App 快速上架经验
- JSON对象长度和遍历方法-前端开发博客
- 价格改革确立时间表和路线图 六大重点领域破题
- iOS --- 音量调节视图MPVolumeView的使用
- 事件对象详解
- Iterator