队列:火车过隧道。。。火车头先进隧道先出隧道、、、先进先出
栈:桶里倒水再倒出。。。先进后出。。。
两个堆栈实现队列与两个队列实现堆栈
package Test2016.test; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; public class Test20160329 { public static void main(String[] args) { /** * @desc 两个堆栈实现队列 * @idea 堆栈:先进后出,队列:先进先出 * */ MyQueue myQueue = new MyQueue(); System.out.println("入队列顺序:"); for (int i = 1; i <= 10; i++) { System.out.print(i + " "); myQueue.push_q(i); } System.out.println(" 用堆栈实现【队列】弹出:"); for (int i = 0; i < 10; i++) { System.out.print(myQueue.pop_q() + " "); } System.out.println(" ######################"); /** * @desc 两个队列实现堆栈 * @idea 堆栈:先进后出,队列:先进先出 * */ MyStack myStack = new MyStack(); System.out.println("入堆栈顺序:"); for (int i = 1; i <= 10; i++) { System.out.print(i + " "); myStack.push_s(i); } System.out.println(" 用队列实现【堆栈】弹出:"); for (int i = 0; i < 10; i++) { System.out.print(myStack.pop_s() + " "); } } } class MyQueue { private Stack<Integer> s1 = null; private Stack<Integer> s2 = null; public MyQueue() { s1 = new Stack<Integer>(); s2 = new Stack<Integer>(); } public Integer push_q(Integer p) { s1.push(p); return p; } public Integer pop_q() { Integer res = null; if (!s2.isEmpty()) { res = s2.pop(); } else { while (!s1.isEmpty()) { res = s1.pop(); s2.push(res); } if (!s2.isEmpty()) { res = s2.pop(); } } return res; } } class MyStack { private Queue<Integer> q1 = null; private Queue<Integer> q2 = null; public MyStack() { q1 = new LinkedList<Integer>(); q2 = new LinkedList<Integer>(); } public Integer push_s(Integer p) { q1.add(p); return p; } public Integer pop_s() { Integer res = null; boolean flag = true; //标识变量 if (q2.size() > 0 && flag == true) { flag = false; while (q2.size() > 0) { if (q2.size() > 0) { res = q2.remove(); q1.add(res); } } q1.remove(res); } else if (q1.size() > 0 && flag == true) { while (q1.size() > 0) { if (q1.size() > 0) { res = q1.remove(); q2.add(res); } } q2.remove(res); } return res; } }
程序运行输出:
入队列顺序: 1 2 3 4 5 6 7 8 9 10 用堆栈实现【队列】弹出: 1 2 3 4 5 6 7 8 9 10 ###################### 入堆栈顺序: 1 2 3 4 5 6 7 8 9 10 用队列实现【堆栈】弹出: 10 9 8 7 6 5 4 3 2 1