开发者

When would it be preferred to implement a priority queue with a Singly Linked List over a Heap?

开发者 https://www.devze.com 2023-03-14 00:26 出处:网络
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.

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 ine开发者_如何学Cfficient 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号