在队列中删除最后一个元素队列、元素

2023-09-12 21:18:03 作者:浓似

我很抱歉,如果我的问题没有涉及到这个网站。

I'm sorry if my question doesn't relate to this website.

我需要删除队列的最后一个元素。 是我可以使用的唯一操作皮克() - 得到的第一个元素,而不删除它,入队(元) - 插入一个元素到队列的后面,出列() - 删除第一个元素,并为IsEmpty() - 真或假队列是否为空。 我可以不使用任何数组或队列帮助我,和要素的数量是不可用的。

I need to remove the last element of a queue. The only operations I may use are Peek() - get the first element without removing it, Enqueue(element) - Insert an element to the back of the queue, Dequeue() - Remove the first element and IsEmpty() - true or false whether the queue is empty. And I can't use any arrays or queues to assist me, and the number of elements is not available.

现在,我想到了一些解决方案,但每次我碰到困难的时间,因为我不知道如何判断当前元素为最后一个元素。

Now, I thought of some solutions, but each time I get stuck since I don't know how to tell if the current element is the last element.

在此先感谢。再次,对不起,如果这是不正确的地方这种类型的问题。

Thanks in advance. And again, sorry if this isn't the right place for this type of questions.

推荐答案

Justin比尔的解决方案是更直截了当。但我认为这可以就地完成,而无需创建另一个队列。

Justin Beal's solution is the more straight forward. But I think it can be done in place, without creating another queue.

object RemoveLast(Queue q) {
    object first = q.Peek();
    object current = null;
    while (true) {
        current = q.Dequeue();
        if (q.Peek() == first) {
            break;
        }
        q.Enqueue(current);
    }
    return current;
}