如何在Java中对堆栈和队列进行反向排序

如何在Java中对堆栈和队列进行反向排序,java,linked-list,stack,queue,Java,Linked List,Stack,Queue,我想在Java中使用堆栈和队列反转输出顺序 这是我的密码: import java.util.*; public class Books { public static void main(String[] args) { Queue<String> book = new LinkedList<String>(); Stack<String> Title = new Stack<>(); S

我想在Java中使用堆栈和队列反转输出顺序

这是我的密码:

import java.util.*;

public class Books {
    public static void main(String[] args) {
        Queue<String> book = new LinkedList<String>();
        Stack<String> Title = new Stack<>();
        Scanner user = new Scanner(System.in);

        System.out.println("Enter four book titles.");
        int b = 4;
        for (int i = 1; i <= b; i++) {
            System.out.print("Book " + i + ": ");
            String Enter = user.nextLine();
            book.offer(Enter);
        }

        System.out.println("New order of books:");
        System.out.println(book);

    }
}

我想做的是按相反的顺序做。但是我不知道该怎么办。

您可以尝试将书籍添加到
队列
中,并将它们添加到
堆栈
中,然后使用
pop()
操作进行打印

如果要使用
堆栈

    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<>();
        Scanner user = new Scanner(System.in);

        System.out.println("Enter four book titles.");
        int b = 4;
        for (int i = 1; i <= b; i++) {
            System.out.print("Book " + i + ": ");
            String Enter = user.nextLine();
            queue.add(Enter);
        }

        ArrayDeque<String> stack = new ArrayDeque<>();
        while (!queue.isEmpty()) {
            stack.push(queue.poll());
        }

        System.out.println("New order of books:");
        while (!stack.isEmpty()) {
            System.out.print(stack.pop()+" ");
        }
        user.close();
    }
利用实现的优势(双端队列)。请注意,
Deque
还实现了(单端队列)

您可以使用该方法将书本插入队列的开头。之后无需反转此类队列。最简单的例子:

Deque<String> queue = new LinkedList<>();
        
for (int i = 1; i <= 4; i++){
    queue.offerFirst("book" + i);
}

System.out.println("Reversed order of books:");
System.out.println(queue);

<强>注1:只要不需要索引访问,就要考虑使用Stimad。


注2:只要考虑到堆栈,就不要使用它。

我认为这个问题与堆栈和队列无关。您可以使用简单的arraylist来实现这一点,任务是“创建一个由(4)个书名组成的java堆栈。逐个弹出所有元素,每个弹出的元素都将添加到一个队列”。这可能吗?你现在说的和你在问题中描述的完全不同。你是什么意思?这就是它在说明中所说的,我们遵循任务中的说明,但最终得到了不同的预期输出。预期的输出是相反的,因为堆栈一个接一个地弹出。“它在指令中说”-什么指令?这个问题没有进一步的说明。所有的问题都是“我想使用java中的堆栈和队列反转输出顺序”。按照你描述的方式去做是没有意义的,除非这是一项学校的任务,是一项练习。在这种情况下,你必须提供这样的信息,否则就别指望会出现这样的答案。
Enter four book titles.
Book 1: wew1
Book 2: wew2
Book 3: wew3
Book 4: wew4
New order of books:
wew4 wew3 wew2 wew1
Deque<String> queue = new LinkedList<>();
        
for (int i = 1; i <= 4; i++){
    queue.offerFirst("book" + i);
}

System.out.println("Reversed order of books:");
System.out.println(queue);
Reversed order of books:
[book4, book3, book2, book1]