在队列中删除最后一个元素 [英] Remove the last element in a queue

查看:944
本文介绍了在队列中删除最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

<一个href="http://programmers.stackexchange.com/questions/40271/remove-the-last-element-in-a-queue/40279#40279">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;
}

这篇关于在队列中删除最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆