有没有办法获取队列中的最后一个元素?

有没有办法获取队列中的最后一个元素?

问题描述:

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

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.