1. 程式人生 > >使用棧Stack實現佇列Queue

使用棧Stack實現佇列Queue

如何只使用stack實現queue呢?由於stack是現進後出(FILO),而queue是先進先出的(FIFO)。也就是說stack進行了一次反向,進行兩次反向就能實現queue的功能,所以可以用兩個stack實現queue。   假設兩個棧inStack和outStack,且都為空。可以認為onStack提供入隊的功能,棧outStack提供出隊的功能。下面是入隊和出隊的具體演算法:(1)如果棧outStack不為空,直接彈出棧outStack頂部的資料;(2)如果棧outStack為空,則依次彈出棧inStack的資料,放入棧outStack中,再彈出棧outStack頂部的資料;實現的程式碼:
  1. /** 
  2.      * 使用兩個棧來模擬佇列 
  3.      *  
  4.      * @param <T> 
  5.      *  
  6.      */
  7.     publicclass SimulationQueue<T> {  
  8.         private Stack<T> inStack;  
  9.         private Stack<T> outStack;  
  10.         public SimulationQueue() {  
  11.             inStack = new Stack<T>();  
  12.             outStack = new
     Stack<T>();  
  13.         }  
  14.         /** 
  15.          * 入隊 
  16.          *  
  17.          * @param t 
  18.          */
  19.         publicvoid enqueue(T t) {  
  20.             inStack.push(t);  
  21.         }  
  22.         /** 
  23.          * 出隊 
  24.          */
  25.         public T dequeue() {  
  26.             T temp = null;  
  27.             if (!outStack.isEmpty()) {  
  28.                 temp = outStack.pop();  
  29.             } else {  
  30.                 while (!inStack.isEmpty()) {  
  31.                     temp = inStack.pop();  
  32.                     outStack.push(temp);  
  33.                 }  
  34.                 if (!outStack.isEmpty()) {  
  35.                     temp = outStack.pop();  
  36.                 }  
  37.             }  
  38.             return temp;  
  39.         }  
  40.         /** 
  41.          * 佇列是否為空 
  42.          *  
  43.          * @return 
  44.          */
  45.         publicboolean isEmpty() {  
  46.             return inStack.isEmpty() && outStack.isEmpty();  
  47.         }  
  48.         /** 
  49.          * 清空佇列 
  50.          */
  51.         publicvoid clear() {  
  52.             inStack.clear();  
  53.             outStack.clear();  
  54.         }  
  55.     }  

測試程式碼:
  1. publicstaticvoid main(String[] args) {  
  2.         SimulationQueue<String> queue = new SimulationQueue<String>();  
  3.         queue.enqueue("a");  
  4.         queue.enqueue("b");  
  5.         queue.enqueue("c");  
  6.         queue.enqueue("d");  
  7.         while(!queue.isEmpty()){  
  8.             System.out.println("當前出隊元素:"+queue.dequeue());  
  9.         }  
  10.     }  

輸出: