-2

Using C# and VisualStudio. I'm trying to intrude everything in one function.

3 Answers3

1

Check the Queue<T>.TryPeek(T) Method

blenderfreaky
  • 738
  • 7
  • 26
1

To get the last element you added to a Queue, which means the last element that will be dequeued, you can just use Last:

var queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue(3);
Console.WriteLine(queue.Last());

Output

3

Note : Peeking will not help, peeking a queue shows you the next dequable item


The long story is, a queue supports IEnumerbale<T>

public class Queue<T> : IEnumerable<T>,
        System.Collections.ICollection,
        IReadOnlyCollection<T> 

Internally, it stores a queue as an array with a capacity and modulates around the array to get the next item so it doesn't need to copy all the time.

IEnumerable.Last will iterate from head to tail using something similar to the following, until it reaches the last item. Which makes it safe to call.

  internal T GetElement(int i)
  {
      return _array[(_head + i) % _array.Length];
  }  

Basically it's an O(n) operation. So, I've you have large queues take into consideration this is not all that efficient. Maybe you want a Stack Instead, or to keep the last item added in memory.

It is just a fancy array.

halfer
  • 19,824
  • 17
  • 99
  • 186
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
-1

Try .Top(). Top() method shows the next element that will be popped in the queue.

Regards,

404_hero
  • 9
  • 2