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

前端 未结 5 1385
鱼传尺愫
鱼传尺愫 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.

    0 讨论(0)
  • 2021-01-26 19:02

    If you really need to you can use this but consider using a different data structure:

    public static class QueueExtensions<T>
    {
        const BindingFlags _flags = 
            BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance;
    
        private static readonly FieldInfo _array =
            typeof(Queue<T>).GetField("_array", _flags);
    
        private static readonly FieldInfo _size = 
            typeof(Queue<T>).GetField("_size", _flags);
    
        public T LastItem(this Queue<T> value)
        {
            if (value == null) 
                throw new ArgumentNullException("value");
            if (value.Count == 0) 
                throw new ArgumentException("The queue cannot be empty.", "value");
            var array = (T[])_array.GetValue(value);
            var size = (int)_size.GetValue(value);
            return array[size - 1];
        }
    }
    
    0 讨论(0)
  • 2021-01-26 19:05

    Queue's are not set up to make that operation fast, so the best you can do is O(n).

    If you import System.Linq, you can write: myQueue.Last()

    0 讨论(0)
  • 2021-01-26 19:13

    You could use LINQ's Enumerable.Last() method (where myQueue is the name of your Queue):

    var lastElement = myQueue.Last();
    

    Although as others have mentioned, if you find yourself needing to do this often, you probably want to think about using a different data structure. For example, a List<T>:

    var myElement = myList[myList.Length - 1];
    
    0 讨论(0)
  • 2021-01-26 19:18

    No, you would have to convert the queue to some other collection (using ToList or ToArray) in order to do this. This would effectively dequeue everything in the queue.

    Keep in mind that by needing the last item from a queue you have effectively proven that you are using the wrong collection to hold your data. Consider changing your collection to another type that provides all the operations you need.

    0 讨论(0)
提交回复
热议问题