There are, of course, several options. The first one I think of uses only 1 queue, but assumes that you know the size of the queue.
The difficulties are not very good, the insert will be linear, popping is constant.
Below is the python python 3 code.
class PriorityQueue(Queue): def insert(self, item): for i in range(self.size): next = self.pop() if next < item: self.enqueue(next) else: self.enqueue(item) self.enqueue(next) break for i in range(i, self.size): self.enqueue(self.pop()) def pop(self): return self.pop()
I used the name self.pop for the first item from the original queue. "Self.enqueue" puts the item at the end of the original queue.
How it works: The insert takes all the smaller elements from the queue and puts them at the end. When the newest item is the smallest, put it at the end. After that, just put the remaining items at the end.
Please note that I did not put the details in my code, for example, the case when the queue is empty, possibly complete ... This code will not work, but it should convey the idea.
Working solution in python 3:
from queue import Queue class PriorityQueue(Queue): def insert(self, item): if self.empty(): self.put(item) return i = 0 size = self.qsize() n = self.get() while item > n and i < size: self.put(n) n = self.get() i += 1 if i == size: self.put(item) self.put(n) for i in range(size): self.put(self.get()) else: self.put(item) self.put(n) for j in range(i + 1, size): self.put(self.get())
Noctua
source share