数据结构-两个栈实现一个队列和两个队列实现一个栈 发表于 2019-04-21 | 分类于 数据结构 两个栈实现一个队列123456789101112131415161718192021222324252627282930import java.util.Stack;/** * Created by cdx0312 * 2018/4/13 */public class TwoStackImpQueue { private Stack<Integer> stack1 = new Stack<>(); private Stack<Integer> stack2 = new Stack<>(); public void push(int node) { stack1.push(node); } public Integer pop() { if (stack2.size() <= 0) { while (stack1.size() > 0) { stack2.push(stack1.pop()); } } if (stack2.isEmpty()) { try { throw new Exception("queue is empty"); } catch (Exception e){ e.printStackTrace(); } } return stack2.pop(); }} 两个队列实现一个栈1234567891011121314151617181920212223242526272829303132333435363738394041424344import java.util.LinkedList;import java.util.Queue;/** * Created by cdx0312 * 2018/4/13 */public class TwoListImpStack { private Queue<Integer> list1 = new LinkedList<>(); private Queue<Integer> list2 = new LinkedList<>(); public void push(int node) { if (list1.isEmpty() && list2.isEmpty()){ list1.add(node); } else if (list1.isEmpty()) { list2.add(node); } else { list2.add(node); } } public Integer pop() { if (list1.isEmpty() && list2.isEmpty()){ try { throw new Exception("stack is Empty!"); } catch (Exception e) { e.printStackTrace(); } } else if (list1.isEmpty()) { while (list2.size() > 1) { list1.add(list2.poll()); } return list2.poll(); } else { while (list1.size() > 1) { list2.add(list1.poll()); } return list1.poll(); } return null; }} Donate comment here 打赏 微信支付 支付宝 比特币