Of course, for any production code, you must rely on a reliable library implementation that has already stood the test of time.
However, for self-study this may be interesting to write yourself. I have done this before.
The most efficient way I know is to use a similar approach to what most modified collections do: store an array that grows in size (usually doubles) as needed when the collection reaches the length of the array.
The queue is slightly different from the regular collection because you want you to be able to jump from the opposite end from which the elements were clicked.
Obviously, to remove the first element and shift all other elements down, one index will be costly and pointless. So instead, you track the start and end indices yourself. When the collection reaches the end of the array, you use % to start pushing items back at the beginning.
The key is simply to work out your math so that you handle all cases, for example, grow the array correctly when the queue is full, correctly evaluate your boundaries, increase the start index (or return to 0) for each pop, etc.
Obviously, the design described above has many limitations: thread safety, for example. But for a simple, single-threaded, efficient implementation, this is a pretty good starting point.
Good luck - and I also recommend publishing your code if / when you have one that you think works!
source share