一.两个栈实现一个队列java
思路:全部元素进stack1,而后所有出stack1并进入stack2.实现队列的先进先出即:若stack2非空,咱们须要的刚好再栈顶,出栈;若要给队列添加元素,即先进sack1,要出队时,若stack2不为空就出栈,为空时就把stack1所有进栈到stack2code
import java.util.Stack; /** * Created by smyhvae on 2015/9/9. */ public class Queue { private Stack<Integer> stack1 = new Stack<>();//执行入队操做的栈 private Stack<Integer> stack2 = new Stack<>();//执行出队操做的栈 //方法:给队列增长一个入队的操做 public void push(int data) { stack1.push(data); } //方法:给队列正价一个出队的操做 public int pop() throws Exception { if (stack2.empty()) {//stack1中的数据放到stack2以前,先要保证stack2里面是空的(要么一开始就是空的,要么是stack2中的数据出完了),否则出队的顺序会乱的,这一点很容易忘 while (!stack1.empty()) { stack2.push(stack1.pop());//把stack1中的数据出栈,放到stack2中【核心代码】 } } if (stack2.empty()) { //stack2为空时,有两种可能:一、一开始,两个栈的数据都是空的;二、stack2中的数据出完了 throw new Exception("队列为空"); } return stack2.pop(); } public static void main(String[] args) throws Exception { Queue queue = new Queue(); queue.push(1); queue.push(2); queue.push(3); System.out.println(queue.pop()); queue.push(4); System.out.println(queue.pop()); System.out.println(queue.pop()); System.out.println(queue.pop()); } }
二.两个队列实现一个栈队列
import java.util.ArrayDeque; import java.util.Queue; /** * Created by smyhvae on 2015/9/9. */ public class Stack { Queue<Integer> queue1 = new ArrayDeque<Integer>(); Queue<Integer> queue2 = new ArrayDeque<Integer>(); //方法:入栈操做 public void push(int data) { queue1.add(data); } //方法:出栈操做 public int pop() throws Exception { int data; if (queue1.size() == 0) { throw new Exception("栈为空"); } while (queue1.size() != 0) { if (queue1.size() == 1) { data = queue1.poll(); while (queue2.size() != 0) { //把queue2中的所有数据放到队列一中 queue1.add(queue2.poll()); return data; } } queue2.add(queue1.poll()); } throw new Exception("栈为空");//不知道这一行的代码是什么意思 } public static void main(String[] args) throws Exception { Stack stack = new Stack(); stack.push(1); stack.push(2); stack.push(3); System.out.println(stack.pop()); System.out.println(stack.pop()); stack.push(4); } }