Replace List in BFS with Queue (#3231)

This commit is contained in:
David Liu 2022-08-27 22:46:58 -07:00 committed by GitHub
parent c500e8ae5a
commit 9e37775506
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2,10 +2,11 @@ package com.thealgorithms.searches;
import com.thealgorithms.searches.DepthFirstSearch.Node; import com.thealgorithms.searches.DepthFirstSearch.Node;
import java.util.ArrayList; import java.util.ArrayDeque;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.Queue;
/** /**
* @author: caos321 * @author: caos321
@ -18,10 +19,10 @@ public class BreadthFirstSearch {
return Optional.of(node); return Optional.of(node);
} }
List<Node> queue = new ArrayList<>(node.getSubNodes()); Queue<Node> queue = new ArrayDeque<>(node.getSubNodes());
while (!queue.isEmpty()) { while (!queue.isEmpty()) {
final Node current = queue.get(0); final Node current = queue.poll();
if (current.getName().equals(name)) { if (current.getName().equals(name)) {
return Optional.of(current); return Optional.of(current);
@ -29,7 +30,7 @@ public class BreadthFirstSearch {
queue.addAll(current.getSubNodes()); queue.addAll(current.getSubNodes());
queue.remove(0); queue.remove();
} }
return Optional.empty(); return Optional.empty();