2012-09-18 68 views

回答

6

您可以使用遞歸函數調用來彈出堆棧,然後您推送正在排隊的項目,然後當遞歸調用展開時,您可以推送彈出的內容。但這實際上是兩個堆棧,因爲系統程序計數器是一個堆棧。

1

遞歸是答案



    public class QueueWithStack 
    { 
     private static Stack stackQueue; 

     public QueueWithStack() 
     { 
     stackQueue = new Stack(); 
     } 

     public void enqueue(int entry) 
     { 
     stackQueue.add(entry); 
     } 

     //dequeue a particular element from queue 
     public void dequeue(int entry) 
     { 
     int popInt; 

     if (!stackQueue.isEmpty()) 
     { 
      popInt = stackQueue.pop(); 
      if (popInt != entry) 
      { 
      dequeue(entry) 
      stackQueue.push(popInt); 
      } 
     } 
     return; 
     } 

     public void dequeueFIFO() 
     { 
     if (!stackQueue.isEmpty()) 
     { 
      int popInt = stackQueue.pop(); 
      if (!stackQueue.isEmpty()) 
      { 
      deququeFIFO(); 
      stackQueue.push(popInt); 
      } 
     } 
     } 
    } 

調用主,創造了QueueWithStack對象,並增加從這個「隊列」移除整數將允許用戶推項目到隊列中,並從訪問任何項目隨時在隊列中,以及按FIFO順序從隊列中刪除項目。

+0

謝謝!好主意! – user144600