有没有办法获取队列中的最后一个元素? [英] Is there a way to get the last element in a Queue?

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

问题描述

我知道堆栈是最好和最简单的方法,但是否有可能获得队列中的最后一个元素而不必出队?

I know stack is best and easiest way, yet could it be possible to obtain the last element in a queue without having to dequeue anything?

推荐答案

您只需:

// Assumes T is a reference type, if it's a value type, then
// you will get an instance with the bits zeroed out.
T item = queue.LastOrDefault();

这里的问题是,每次想要获取队列中的最后一项时,都必须遍历队列中的项.

The problem here is that every time you want to get the last item in the Queue, you have to iterate through every item in the queue.

如果访问队列的第一个和最后一个元素对您很重要,那么您可能需要考虑 双端队列.

If it's important to you to have access to the first and last elements of a queue, then you might want to consider a double-ended queue.

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

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