java - Reverse 方法反转队列的元素

标签 java

这不是硬件或作业。这是我自己在练习的东西。

给定一个队列,编写一个 Reverse 方法来反转队列中的元素。 MyQueue 保持不变。

签名:

public Queue<T> reverse(Queue<T> myQueue) {

注意:不知道Queue是用节点还是数组做的。

队列已经实现了我们可以使用的方法:

void enqueue(T element)
T dequeue();
boolean isFull();
boolean isEmpty();
int size();

最佳答案

您可以使用堆栈来反转队列。

在 Java 中是这样的:

public void reverse(Queue q)
{
    Stack s = new Stack();  //create a stack

    //while the queue is not empty
    while(!q.isEmpty())
    {  //add the elements of the queue onto a stack
       s.push(q.serve());
    } 

    //while the stack is not empty
    while(!s.isEmpty())
    { //add the elements in the stack back to the queue
      q.append(s.pop());
    }

}

The append and serve methods of the queue are to add and remove elements of that queue.

这是一个例子:

队列有元素:

1 2 3 4

当元素被添加到堆栈时,数字 1 将位于列表底部,4 位于顶部:

1 2 3 4 <- 顶部

现在弹出堆栈并将元素放回队列中:

4 3 2 1

希望对您有所帮助。

关于java - Reverse 方法反转队列的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16857276/

相关文章:

java - Spring mvc 使用 @RequestBody 验证原语不起作用

java - 在 Android 客户端应用程序中混淆 URL

java - 如何使用java进行Web服务负载测试?

java - 在java中部署Web服务

java - 从特定位置(键)向后有效地迭代/子映射 TreeMap

Java:如何指定一个目录,这样我就不需要指定它来引用它的 .jar 文件

java - 不允许启动服务 Intent - Android Oreo

java - 查找所有 UUID MongoRepository

java - Java 中的 Setter 和 Getter

java - 使用 Java Mail API 向单独的收件人发送批量邮件