什么时候最好使用单链表而不是堆来实现优先级队列?

发布于 2024-11-16 10:39:05 字数 167 浏览 3 评论 0原文

我最近刚刚启动了一个项目,其中一些代码已经编写完毕。我决定研究他的实现,发现他实现了带有单链表的优先级队列。

我对 SLL 的理解是,由于您可能必须迭代整个列表,因此实现它的效率很低,这就是为什么堆是首选的原因。然而,也许我缺少其背后的某种推理,并且想知道是否有人选择过 SLL 而不是堆作为优先级队列?

I recently just started up a project with some code that has been already written. I decided to look into his implementation and found that he implemented a Priority Queue with a Singly Linked List.

My understanding of SLLs is that since you may have to iterate over the entire list, it's inefficient to implement it as such, which is why Heaps are preferred. However, perhaps I am missing some sort of reasoning behind it and was wondering if anyone has ever chosen an SLL over a Heap for a Priority Queue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半寸时光 2024-11-23 10:39:05

在某些情况下,SLL 比堆更适合实现优先级队列。例如:

  1. 当需要尽可能快地从队列中删除时。从 SLL 中删除的时间复杂度为 O(1)(从列表/队列的前面),而从堆中删除的时间复杂度为 O(log n)。实际上,我在为简单操作系统编写alarm() 系统调用版本时遇到了这个问题。我根本无法承受 O(log n) 的查找时间。与此相关的是当您需要一次删除多个元素时。从 SLL 中删除 k 个元素需要 O(k) 时间,而对于堆则需要 O(k log n) 时间。
  2. 内存问题。最小或最大堆的传统实现涉及一个数组,该数组需要随着堆的增长而调整大小。如果您无法承担进行大型realloc所需的时间,那么此策略就不再适用。如果将堆实现为一棵二叉树,则需要两个指针,而不是 SLL 的一个指针。
  3. 当你必须保持多个优先事项时。跟踪不同链表中的相同节点相对容易。使用堆执行此操作要复杂得多。

There are situations where a SLL is better than a heap for implementing a priority queue. For example:

  1. When removing from the queue needs to be as fast as possible. Removing from an SLL is O(1) (from the front of the list/queue) while removing from a heap is O(log n). I actually ran into this while writing a version of the alarm() syscall for a simple OS. I simply could not afford the O(log n) lookup time. Related to this is when you need to remove multiple elements at a time. Removing k elements from an SLL takes O(k) time while it takes O(k log n) time for a heap.
  2. Memory issues. The traditional implementation of a min or max heap involves an array, which needs to be resized as the heap grows. If you can't afford the time it takes to do a large realloc then this strategy is out. If you implement the heap as a binary tree, then you need two pointers instead of one for an SLL.
  3. When you have to maintain multiple priorities. It is relatively easy to keep track of the same nodes in different linked lists. Doing this with heaps is much more complicated.
不交电费瞎发啥光 2024-11-23 10:39:05

在大学里,有人告诉我,我们使用链表的唯一原因是帮助我们理解指针。

In college I was told that the only reason we were made to use Linked Lists was to help us with our understanding of pointers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文