使用GenericQueue以相反顺序打印用户输入的单词。JAVA
我对一般队列感到困惑。由于只添加元素(queue.enqueue)并从中删除元素(queue.deqque),如何显示来自用户输入的反向单词 更具体地说,我有以下java代码使用GenericQueue以相反顺序打印用户输入的单词。JAVA,java,queue,stack,Java,Queue,Stack,我对一般队列感到困惑。由于只添加元素(queue.enqueue)并从中删除元素(queue.deqque),如何显示来自用户输入的反向单词 更具体地说,我有以下java代码 import java.util.Scanner; public class displayreverse { public static void main(String[] args) { Scanner input = new Scanner(System.in); GenericQ
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);
}
}
我将如何使用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();
}
}
public类GenericQueue{
private java.util.LinkedList=new java.util.LinkedList();
公共空间排队(E){
列表。添加最后一个(e);
}
公共E出列(){
return list.removeFirst();
}
公共int getSize(){
返回list.size();
}
公共字符串toString(){
返回“Queue;”+list.toString();
}
}
感谢…在
GenericQueue
中创建enqueueFirst
方法,将元素添加到前面(或将enqueue
更改为add in front not last)
用于使用enqueueFirst
接收同一行中的单词,如下所示:
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
}
Rest看起来不错。为什么要使用GenericQueue,因为它是后进先出(LIFO)排序,所以通常要使用堆栈进行反向操作。而队列是先进先出(FIFO)。也许可以使用您自己的类扩展GenericQueue类,该类实现addItem函数以添加到列表的前面而不是末尾。
public void enqueueFirst(E e){
list.addFirst(e);
}
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
}