CLRS10.1-6練習 - 用雙棧實現隊列
雙棧實現隊列算法:
分別考慮隊列兩種操作入隊和出隊,我們假設使用棧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 }
不甘于現在,便行動于現在

浙公網安備 33010602011771號