Is there a way to get the last element in a Queue?

前端 未结 5 1398
鱼传尺愫
鱼传尺愫 2021-01-26 18:26

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?

5条回答
  •  孤独总比滥情好
    2021-01-26 18:58

    You can simply do:

    // 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.

提交回复
热议问题