【发布时间】:2018-04-14 04:37:31
【问题描述】:
我正在尝试使用卡恩算法编写一个程序,有点与 BFS 相关。由于 Queue 和 List 有确切的键被放入,有没有办法删除队列并使列表像队列一样执行并且仍然返回值?我被告知要保留对 List 的偏好,而不是像队列那样删除键。我不知道该怎么做。任何建议表示赞赏。这是我的程序的一部分。
private static List<Job> topologicalSortBFS(final List<Job> jobs) //Kahn's
{
final List<Job> sorted = new ArrayList<>(jobs.size());
final Map<Job, Integer> inCount = new HashMap<>(jobs.size());
final Queue<Job> queue = new ArrayDeque<>();
for (final Job j : jobs)
{
/* Associate every node with the amount of nodes it requires. */
final int in = j.inbound.size();
inCount.put(j, in);
/* If the node requires nothing, then add to queue and sorted list. */
if (in == 0)
{
sorted.add(j);
queue.add(j);
}
}
while (!queue.isEmpty())
{
final Job current = queue.poll(); // poll = pop
for (final Job neighbor : current.outbound)
{
/* Remove an outgoing connection without modifying the node. */
final int updatedIncount = inCount.get(neighbor) - 1;
inCount.put(neighbor, updatedIncount);
/* If node is now considered a leaf, its requirements were met. */
if (updatedIncount == 0)
{
sorted.add(neighbor);
queue.add(neighbor);
}
}
}
return sorted;
}
【问题讨论】:
-
欢迎来到 SO。 LinkedList 是一个 List :
List<Job> list = new LinkedList();,支持队列和堆栈功能。
标签: java list sorting queue breadth-first-search