首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何让列表像队列一样工作,同时仍然返回值?

如何让列表像队列一样工作,同时仍然返回值?
EN

Stack Overflow用户
提问于 2018-04-14 12:37:31
回答 1查看 160关注 0票数 0

我正在试着写一个使用Kahn算法的程序,有点像BFS。由于队列和列表中有确切的键被放入,有没有办法删除队列并使列表像队列一样执行,并且仍然返回值?我被告知要保留列表的首选项,而不是像队列那样删除键。不过,我不知道该怎么做。任何建议都是值得感谢的。这是我程序的一部分。

代码语言:javascript
运行
复制
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;
    }
EN

回答 1

Stack Overflow用户

发布于 2018-04-14 13:16:18

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

备注:Queue最适合于给定的示例,我的答案只是根据您的问题使用列表的一种变通方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49827980

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档