2012-11-13 44 views
0

我對GenericQueue感到困惑。只添加元素(queue.enqueue)並從中刪除元素(queue.dequque),如何顯示來自用戶輸入的反向字詞?使用GenericQueue以相反的順序打印用戶輸入的單詞。 Java

更具體地說,我有下面的java代碼。

import java.util.Scanner; 

public class displayreverse { 
public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     GenericQueue<String> queue = new GenericQueue<String>(); 
     System.out.print("Enter some words: "); 
     String words = input.nextLine(); 

     queue.enqueue(words); 
     System.out.println(queue); 

    } 
} 

輸出將是這樣的:

run: 
Enter some words: who are you 
Queue; [who are you] 

我將如何使用GenericQueue,以便它以相反的順序顯示呢?輸出應該是這樣的:「你是誰」,而不是「你是誰」

我GenericQueue類如下:

public class GenericQueue<E> { 
    private java.util.LinkedList<E> list = new java.util.LinkedList<E>(); 
      public void enqueue(E e){ 
       list.addLast(e); 
      } 
      public E dequeue(){ 
       return list.removeFirst(); 
      } 
      public int getSize(){ 
       return list.size(); 
      } 
      public String toString(){ 
       return "Queue; " + list.toString(); 
      } 
} 

謝謝...

+0

爲什麼使用GenericQueue,通常是因爲它是後進先出(LIFO)排序而使用堆棧。而隊列先進先出(FIFO)。也許使用你自己的類來擴展GenericQueue類,該類實現了addItem函數來添加到列表的前面而不是結尾。 – Genzume

回答

1

GenericQueue作爲創建enqueueFirst方法添加在前面的元件(或改變enqueue到在前面加不會持續)

public void enqueueFirst(E e){ 
    list.addFirst(e); 
    } 

對於使用0123的所有接收在同一行的字如下:

System.out.print("Enter some words: "); 
    String wordsLine = input.nextLine(); 
    String[] words = wordsLine.split(" ");//split the words separated by space 
    for(String word: words){ 
     queue.enqueueFirst(word);//add one word at a time 
    } 

休息看起來不錯。

+0

非常感謝你!它真的幫了很多! – user1657294

相關問題