




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





This chapter presents two ADTs: the Queue and the Priority Queue. In real life, a queue is a line of customers waiting for service of some kind. In most cases, the first customer in line is the next customer to be served. There are exceptions, though. At airports, customers whose flights are leaving soon are sometimes taken from the middle of the queue. At supermarkets, a polite customer might let someone with only a few items go first.
The rule that determines who goes next is called the queueing policy. The simplest queueing policy is called FIFO, for āfirst-in-first-out.ā The most gen- eral queueing policy is priority queueing, in which each customer is assigned a priority and the customer with the highest priority goes first, regardless of the order of arrival. We say this is the most general policy because the priority can be based on anything: what time a flight leaves; how many groceries the customer has; or how important the customer is. Of course, not all queueing policies are āfair,ā but fairness is in the eye of the beholder.
The Queue ADT and the Priority Queue ADT have the same set of operations. The difference is in the semantics of the operations: a queue uses the FIFO policy; and a priority queue (as the name suggests) uses the priority queueing policy.
The Queue ADT is defined by the following operations:
init : Initialize a new empty queue.
insert: Add a new item to the queue.
198 Queues
remove: Remove and return an item from the queue. The item that is returned is the first one that was added.
isEmpty: Check whether the queue is empty.
The first implementation of the Queue ADT we will look at is called a linked queue because it is made up of linked Node objects. Here is the class definition:
class Queue: def init(self): self.length = 0 self.head = None
def isEmpty(self): return (self.length == 0)
def insert(self, cargo): node = Node(cargo) node.next = None if self.head == None:
self.head = node else:
last = self.head while last.next: last = last.next
last.next = node self.length = self.length + 1
def remove(self): cargo = self.head.cargo self.head = self.head.next self.length = self.length - 1 return cargo
The methods isEmpty and remove are identical to the LinkedList methods isEmpty and removeFirst. The insert method is new and a bit more compli- cated.
We want to insert new items at the end of the list. If the queue is empty, we just set head to refer to the new node.
200 Queues
The ImprovedQueue implementation looks like this:
class ImprovedQueue: def init(self): self.length = 0 self.head = None self.last = None
def isEmpty(self): return (self.length == 0)
So far, the only change is the attribute last. It is used in insert and remove methods:
class ImprovedQueue: ... def insert(self, cargo): node = Node(cargo) node.next = None if self.length == 0:
self.head = self.last = node else:
last = self.last
last.next = node self.last = node self.length = self.length + 1
Since last keeps track of the last node, we donāt have to search for it. As a result, this method is constant time.
There is a price to pay for that speed. We have to add a special case to remove to set last to None when the last node is removed:
class ImprovedQueue: ... def remove(self): cargo = self.head.cargo self.head = self.head.next self.length = self.length - 1 if self.length == 0: self.last = None return cargo
19.5 Priority queue 201
This implementation is more complicated than the Linked Queue implementa- tion, and it is more difficult to demonstrate that it is correct. The advantage is that we have achieved the goalāboth insert and remove are constant-time operations.
As an exercise, write an implementation of the Queue ADT using a Python list. Compare the performance of this implementation to the ImprovedQueue for a range of queue lengths.
The Priority Queue ADT has the same interface as the Queue ADT, but different semantics. Again, the interface is:
init : Initialize a new empty queue.
insert: Add a new item to the queue.
remove: Remove and return an item from the queue. The item that is returned is the one with the highest priority.
isEmpty: Check whether the queue is empty.
The semantic difference is that the item that is removed from the queue is not necessarily the first one that was added. Rather, it is the item in the queue that has the highest priority. What the priorities are and how they compare to each other are not specified by the Priority Queue implementation. It depends on which items are in the queue.
For example, if the items in the queue have names, we might choose them in alphabetical order. If they are bowling scores, we might go from highest to lowest, but if they are golf scores, we would go from lowest to highest. As long as we can compare the items in the queue, we can find and remove the one with the highest priority.
This implementation of Priority Queue has as an attribute a Python list that contains the items in the queue.
class PriorityQueue: def init(self): self.items = []
def isEmpty(self): return self.items == []
19.6 The Golfer class 203
As an example of an object with an unusual definition of priority, letās implement a class called Golfer that keeps track of the names and scores of golfers. As usual, we start by defining init and str :
class Golfer: def init(self, name, score): self.name = name self.score= score
def str(self): return "%-16s: %d" % (self.name, self.score) str uses the format operator to put the names and scores in neat columns.
Next we define a version of cmp where the lowest score gets highest priority. As always, cmp returns 1 if self is āgreater thanā other, -1 if self is āless thanā other, and 0 if they are equal.
class Golfer: ... def cmp(self, other): if self.score < other.score: return 1 # less is more if self.score > other.score: return - return 0
Now we are ready to test the priority queue with the Golfer class:
>>> tiger = Golfer("Tiger Woods", 61) >>> phil = Golfer("Phil Mickelson", 72) >>> hal = Golfer("Hal Sutton", 69) >>> >>> pq = PriorityQueue() >>> pq.insert(tiger) >>> pq.insert(phil) >>> pq.insert(hal) >>> while not pq.isEmpty(): print pq.remove() Tiger Woods : 61 Hal Sutton : 69 Phil Mickelson : 72
As an exercise, write an implementation of the Priority Queue ADT using a linked list. You should keep the list sorted so that removal is a constant time operation. Compare the performance of this imple- mentation with the Python list implementation.
204 Queues
queue: An ordered set of objects waiting for a service of some kind.
Queue: An ADT that performs the operations one might perform on a queue.
queueing policy: The rules that determine which member of a queue is re- moved next.
FIFO: āFirst In, First Out,ā a queueing policy in which the first member to arrive is the first to be removed.
priority queue: A queueing policy in which each member has a priority de- termined by external factors. The member with the highest priority is the first to be removed.
Priority Queue: An ADT that defines the operations one might perform on a priority queue.
linked queue: An implementation of a queue using a linked list.
constant time: An operation whose runtime does not depend on the size of the data structure.
linear time: An operation whose runtime is a linear function of the size of the data structure.