java:使用ArrayDeque或LinkedList或LinkedBlockingDeque进行非递归深度优先搜索?
public void traverse(Node root){
ArrayDeque<Node> queue = new ArrayDeque<Node>();
queue.add(root);
while(!queue.isEmpty()){
Node currentNode = queue.pollFirst();
List<Node> nl = getChildrenfromDB(currentNode);
queue.addAll(nl);
}
那么我应该使用 ArrayDeque 或 LinkedList 或 LinkedBlockingDeque 吗?当我将 int 值设置为 10 时会发生什么?这是否意味着队列一次只能容纳 10 个?如果从数据库中检索的集合大小大于 10 怎么办?这个绑定值是否定义了队列的“快照”?
public void traverse(Node root){
LinkedBlockingDeque<Node> queue = new LinkedBlockingDeque<Node>(10);
queue.add(root);
while(!queue.isEmpty()){
Node currentNode = queue.pollFirst();
List<Node> nl = getChildrenfromDB(currentNode);
queue.addAll(nl);
}
public void traverse(Node root){
ArrayDeque<Node> queue = new ArrayDeque<Node>();
queue.add(root);
while(!queue.isEmpty()){
Node currentNode = queue.pollFirst();
List<Node> nl = getChildrenfromDB(currentNode);
queue.addAll(nl);
}
so should I be using ArrayDeque
or LinkedList
or LinkedBlockingDeque
? what would happen when I set int value of 10? Does this mean the queue will only hold 10 at a time? what if the Collection retrieved from DB's size is larger than 10? Is this bound value define the "snapshot" of the queue?
public void traverse(Node root){
LinkedBlockingDeque<Node> queue = new LinkedBlockingDeque<Node>(10);
queue.add(root);
while(!queue.isEmpty()){
Node currentNode = queue.pollFirst();
List<Node> nl = getChildrenfromDB(currentNode);
queue.addAll(nl);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要使用
ArrayList
——使用Deque
接口的实现之一。例如,使用LinkedBlockingDeque
,它是为此类事情而设计的。根据需要使用addFirst()
、addLast()
、pollFirst()
和pollLast()
方法。如果出于某种原因,您确实需要使用
List
,请使用LinkedList
—— 添加到ArrayList
的前面效率极低,因为所有元素都需要移动。Don't use an
ArrayList
-- use one of the implementations of theDeque
interface. For example, use aLinkedBlockingDeque
, which is designed for this sort of thing. Use theaddFirst()
,addLast()
,pollFirst()
, andpollLast()
methods as needed.If, for some reason, you really need to use a
List
, use aLinkedList
-- adding to the front of anArrayList
is extremely inefficient, as all elements need to be moved.您可以阅读 ArrayList 的 javadocs
JavaDocs 是您的朋友。
话虽这么说,正如其他人提到的;不是最好使用的数据结构。如果不需要随机访问列表,LinkedList 或 ArrayDeque 会更有效。
You could read the javadocs for ArrayList
JavaDocs are your friend.
That being said, as others have mentioned; not the best data structure to use. If you don't need random access into the list, a LinkedList or ArrayDeque are more efficient.
为什么不使用堆栈。堆栈是 DFS 的最佳选择。请参阅这篇文章了解为什么 Stack 可以解决该问题。另请参阅这个有用的教程 :)
Why do not you use Stacks. Stack is the way to go for DFS. See this article to see why Stack will solve the problem. See this useful tutorial also :)