【问题标题】:How to make a list perform like a queue and still return values?如何使列表像队列一样执行并且仍然返回值?
【发布时间】: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&lt;Job&gt; list = new LinkedList(); ,支持队列和堆栈功能。

标签: java list sorting queue breadth-first-search


【解决方案1】:

在您给定的代码中,只有 poll( ) 方法不适用于 List 对象。但是,poll( )FIFO 的方式工作,返回并从队列中移除最顶层的对象。或者,对于List,您可以使用索引值为0 的get(index) 方法获取第一个元素并将其删除。但是您应该考虑使用LinkedList,因为对于remove( ) 操作,ArrayList 中的所有元素将在每次删除时移动,这是一项昂贵的操作。此外,LinkedList 具有 poll( ) 方法,因为它实现了 Queue 接口。

注意:队列最适合给定的示例,我的回答只是根据您的问题使用列表的解决方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    • 2022-09-29
    • 2021-01-19
    • 1970-01-01
    • 2016-06-24
    • 2021-06-25
    相关资源
    最近更新 更多