How do I get the nth item in a Queue?

假如想象 提交于 2019-12-07 05:53:35

问题


I have a number of queues and priority queues in my application. I would like to easily access the nth items in these queues, but don't see an easy way to do that using the API.

I guess I could create an Iterator and iterate to the nth element or use toArray()[index], but it seems like there should be an easier way.

Am I missing something?


回答1:


Am I missing something?

Yes - the fact that accessing elements by index is not part of the concept of a queue.

If you need to access elements by index, you want a list, not a qeue.




回答2:


The simplest solution for you is to use a binary search tree that is self-balancing, e.g. AVL tree, splay tree or red-black tree. It allows you to access elements by their key in O(log n) time and iterate through the objects in their order in O(log n + k) where k is the number of elements iterated..!!




回答3:


The entire point of a queue is to expose access only to the head (the first element). If you want arbitrary access to elements in a linear data structure, use a List (if you're doing a lot more lookups than push/pops, consider using an ArrayList as LinkedLists are not optimized for random access).




回答4:


I have a number of queues and priority queues in my application

What concrete data type are you using for Queues? A LinkedList?In this case you should be able to get the nth element by casting back to linked list.

But this is not how you would use a Queue

As for the priority queue, from you question it seems that you are also not using the correct data structures.

Priority Queue will always return the min element (by ordering).
So what do you mean the n element here?The n smallest or the n inserted or what? So we can't really say what to do in this case




回答5:


Queues don't allow random, indexed access by concept so it is a good thing that the interface does not allow this either. If you need both kinds of access at the same time (which is a bad sign for design) then you could use a datatype that implements both List and Queue (e.g. LinkedList).



来源:https://stackoverflow.com/questions/9637631/how-do-i-get-the-nth-item-in-a-queue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!