剑指Offer-7-用两个栈实现队列/用两个队列实现栈
2015-09-26 19:04
399 查看
1.两个栈实现队列
import java.util.Stack; public class CQueue<T> { private Stack<T> s1 = new Stack<>(), s2 = new Stack<>(); public void EnQueue(T value) { s1.push(value); } public T DeQueue() throws Exception { while (!s1.isEmpty()) { T value = s1.pop(); s2.push(value); } if (!s2.isEmpty()) { return s2.pop(); } else { throw new Exception("queue is empty"); } } public static void main(String[] args) throws Exception { CQueue<Integer> q = new CQueue<>(); q.EnQueue(1); q.EnQueue(2); q.EnQueue(3); System.out.println(q.DeQueue()); System.out.println(q.DeQueue()); System.out.println(q.DeQueue()); } }
2.两个队列实现栈
import java.util.LinkedList; import java.util.Queue; public class CStack<T> { private Queue<T> q1 = new LinkedList<>(), q2 = new LinkedList<>(); public void push(T value) { if (!q2.isEmpty()) { q2.add(value); } else { q1.add(value); } } public T pop() throws Exception { if (q1.isEmpty() && q2.isEmpty()) { throw new Exception("stack is empty."); } T head = null; if (q1.isEmpty()) { while (q2.size() > 1) { T v = q2.poll(); q1.add(v); } head = q2.poll(); } else { while (q1.size() > 1) { T v = q1.poll(); q2.add(v); } head = q1.poll(); } return head; } public static void main(String[] args) throws Exception { CStack<Integer> s = new CStack<>(); s.push(1); s.push(2); s.push(3); System.out.println(s.pop()); System.out.println(s.pop()); System.out.println(s.pop()); } }
相关文章推荐
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析
- C#获取关键字附近文字算法实例