双栈实现队列算法:
分别考虑队列两种操作入队和出队,我们假设使用栈s1 s2,
s1用来模拟入队,s2用来模拟出队
入队:
入队操作直接执行s1.push即可
出队:
代码实现
1 package hello; 2 import java.util.*; 3 4 public class TwoStackOneQueue<E> { 5 private Stack<E> s1 = new Stack<>(); 6 private Stack<E> s2 = new Stack<>(); 7 8 public void enqueue(E item){ 9 s1.push(item); 10 } 11 12 public E dequeue(){ 13 if (s2.empty()){ 14 if(s1.empty()){ 15 throw new ArrayIndexOutOfBoundsException(); 16 }else{ 17 popS1ToS2(); 18 return s2.pop(); 19 } 20 }else{ 21 return s2.pop(); 22 } 23 } 24 25 private void popS1ToS2(){ 26 while(!s1.empty()){ 27 s2.push(s1.pop()); 28 } 29 } 30 31 public static void main(String[] args){ 32 TwoStackOneQueue<Integer> tsoq = new TwoStackOneQueue<>(); 33 for (int i = 0; i < 20; i++){ 34 tsoq.enqueue(i); 35 } 36 for (int i = 0; i < 10; i++) { 37 System.out.println(tsoq.dequeue()); 38 } 39 for (int i = 20; i < 40; i++){ 40 tsoq.enqueue(i); 41 } 42 for (int i = 0; i < 30; i++) { 43 System.out.println(tsoq.dequeue()); 44 } 45 } 46 }