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