这不是硬件或作业。这是我自己在练习的东西。
给定一个队列,编写一个 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/