When would it be preferred to implement a priority queue with a Singly Linked List over a Heap?
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:
- 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. - 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. - 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.
精彩评论